Python编程 字符串的方法

  • 作者简介:一名在校计算机学生、每天分享Python的学习经验、和学习笔记。 

  •  座右铭:低头赶路,敬事如仪

  • 个人主页:网络豆的主页​​​​​​

目录

前言

一字符串

1.字符串常见操作(熟悉)

 2.S.find(sub)、 S.index(sub)

3.replace(old, new[, count])

4.S.split(sep=None)

5.S.startswith 与 S.endswith

6.S.upper 与 S.lower

7.S.strip

8.S.join


前言

本章将会从python 编程 字符串的常见操作去进行讲解。


一字符串

1.字符串常见操作(熟悉)

S.find(sub) --> 返回该元素最小的索引
S.index(sub) --> 返回该元素最小的索引
S.replace(old, new[, count]) --> 替换
S.split(sep=None) --> 以sep来分割字符串,并返回列表。sep默认为None,分割默认为空格
S.startswith(prefix[, start[, end]]) --> 判断字符串是否以前缀开始,返回为bool值。
S.endswith(suffix[, start[, end]]) --> 判断字符串是否以尾缀结束,返回为bool值。
S.lower() --> 将字符串全部转为小写
S.upper() --> 将字符串全部转为大写
S.strip([chars]) --> 默认去掉字符串左右的空格
S.isalpha() --> 判断字符串是否全为字母,返回的是bool值
S.isdigit() --> 判断字符串是否全为数字,返回的是bool值
S.isalnum() --> 判断字符串是否全为数字或者字母,不存在特殊字符,返回的是bool值
S.join(iterable) --> 将序列中的元素以指定的字符连接生成一个新的字符串

 2.S.find(sub)、 S.index(sub)

s1 = "hello python"
print(s1.find("e"))      # S.find(sub[, start[, end]]) -> int 整数   返回最小索引位置

print(s1.find("o"))      #输出得4

print(s1.find("c"))      # 没有C得负一   Return -1 on failure.

print(s1.rfind("o"))     #得10 


print(s1.index("c"))       #ValueError: substring not found  index与find作用一模一样.但是                
                            区别在于当通过S.index查询 不存在的字符串时会报错,而s.find()返回—1

3.replace(old, new[, count])

s2 = "hello oldoldamy"

#old————>beautiful
print(s2.replace("old","beautiful"))   #得hello beautifulbeautifulamy  全部替换掉

print(s2.replace("old","beautiful",1))  #得hello beautifuloldamy    count:指定替换次数

print(s2)           #得 hello oldoldamy    copy of S,所以意味着没有改变s2本身

4.S.split(sep=None)

s3 = "hello everybody yeyeye!"

# 以空格将三个单词进行拆分为列表的元素
print(s3.split(" "))    #['hello', 'everybody', 'yeyeye!']
#返回列表
print(type(s3.split(" ")))   #<class 'list'>

5.S.startswith 与 S.endswith

s4 = "hello everybody yeyeye!"

print(s4.startswith("he"))        #用于判断字符串以什么前缀开始,返回为   

#S.startswith(prefix[, start[, end]]) -> bool

print(s4.endswith("ye!"))          #判断以什么尾椎结束的

6.S.upper 与 S.lower

s5 = "n"
print(s5.upper())    #得N
# Return a copy of the string converted to uppercase

s6 = "Y"
print(s6.lower())    #得y

7.S.strip

s7 = "    一代    枭雄       "
print(s7.strip())   #得一代    枭雄   去除首部以及尾部的空格
print(s7.replace(" ",""))      #一代枭雄  去除中间空格

8.S.join

s8 = "你好某某同学bababalalallaal"

# 实现:"你 好"
# 字符串序列-->一个个取出它的子元素-->可以迭代的(iterable)
print(" ".join(s8))   #得你 好 某 某 同 学 b a b a b a l a l a l l a a l



li = ["你好", "世界"]

# 实现:"你好 世界"
print(" ".join(li))       #得  你好 世界

创作不易,求关注,点赞,收藏,谢谢~

评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

网络豆

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值