python 字符串常用方法

1、find 方法

(1)参数说明及用法

find(sub, start=None, end=None)
# sub:查找的字符串
# start:起始索引
# end:结束索引

返回值为查找字符串的索引

(2)在索引start和end之间查找字符串sub​找到,则返回最左端的索引值,未找到,则返回-1

source_str = "There is a string accessing example"
print(source_str.find('T', 2, 10))
# 输出结果
-1

(3)start和end都可省略,省略start说明从字符串开头找省略end说明查找到字符串结尾,全部省略则查找全部字符串

source_str = "There is a string accessing example"
print(source_str.find('T'))
# 输出结果
0

2、count 方法

(1)参数说明及用法

count(sub, start=None, end=None)
# sub:查找的字符串
# start:起始索引
# end:结束索引

返回值为查找字符串的个数

(2)返回字符串sub在start和end之间出现的次数

source_str = "There is a string accessing example"
print(source_str.count('e'))
print(source_str.count('e', 0, 4))

#输出结果
5
1

3、replace 方法

(1)参数说明及用法

replace(old, new, count=None)

# old代表需要替换的字符,new代表将要替代的字符,count代表替换的次数(省略则表示全部替换)

(2)效果展示

source_str = "There is a string accessing example"
print(source_str.replace('e', 'E'))
print(source_str.replace('e', 'E', 1))

# 结果展示
ThErE is a string accEssing ExamplE
ThEre is a string accessing example

4、spilt 方法

(1)参数说明及用法

split(sep, maxsplit=None)

# 以sep为分隔符切片,如果maxsplit有指定值,则仅分割maxsplit个字符串分割后原来的str类型将转换成list类型

(2)结果展示

source_str = "There is a string accessing example"
print(source_str.split('e'))
print(source_str.split('e', maxsplit=3))

# 输出结果
['Th', 'r', ' is a string acc', 'ssing ', 'xampl', '']
['Th', 'r', ' is a string acc', 'ssing example']

5、startswith 方法

(1)参数说明及用法

startswith(prefix, start=None, end=None)

# 判断字符串是否是以prefix开头,start和end代表从哪个下标开始,哪个下标结束

(2)结果展示

source_str = "There is a string accessing example"
print(source_str.startswith('T', 0, 10))
print(source_str.startswith('T'))

# 输出结果
True
True

6、endswith 方法

(1)参数说明及用法

endswith(suffix, start=None, end=None)

# 判断字符串是否以suffix结束,如果是返回True,否则返回False

(2)结果展示

source_str = "There is a string accessing example"
print(source_str.endswith('e'))
print(source_str.endswith('e', 0, 10))

# 输出结果
True
False

7、lower 方法

(1)参数说明及用法

source_str.lower()

(2)结果展示

source_str = "There is a string accessing example"
print(source_str.lower())
# 将所有字符串变小写

结果:
there is a string accessing example

8、upper 方法

(1)参数说明及用法

source_str.upper()

(2)结果展示

source_str = "There is a string accessing example"
print(source_str.upper())
# 将所有字符串变小写

结果:
THERE IS A STRING ACCESSING EXAMPLE

9、join 方法

(1)使用方法

# 将列表对象拼接成字符串

(2)结果展示

data = ['a', 'b', 'c']
print(''.join(data))

结果展示
abc

10、字符串翻转

source_str = "There is a string accessing example"
print(source_str[::-1])

结果展示
elpmaxe gnissecca gnirts a si erehT
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值