Python-字符串相关方法

Python字符串方法示例

1. len(s)

返回字符串 s 的长度

s = 'hello' 
print(len(s)) # 5

2. s.lower() 和 s.upper()

将字符串转换为全部小写/大写

s = 'Hello'
print(s.lower()) # hello 
print(s.upper()) # HELLO

3. s.strip()

去除字符串两端的空白符

s = ' hello '
print(s.strip()) # 'hello'

4. s.lstrip() 和 s.rstrip()

去除字符串左端/右端的空白符

s = ' hello ' 
print(s.lstrip()) # 'hello '
print(s.rstrip()) # ' hello'

5. s.count(substr)

返回子字符串 substr 在 s 中出现的次数

s = 'hello world'
print(s.count('l')) # 3

6. s.replace(old, new)

将 s 中的 old 子字符串替换为 new

s = 'hello world'
print(s.replace('world', 'Python')) # 'hello Python'

7. s.split(sep)

根据分隔符 sep 分割字符串,返回分割后的列表

s = 'hello world' 
print(s.split()) # ['hello', 'world']

8. s.join(iterable)

使用字符串 s 作为分隔符,将可迭代对象 iterable 中的所有元素合并为一个新的字符串

s = '-'
seq = ['a', 'b', 'c'] 
print(s.join(seq)) # 'a-b-c'

9. s.find(sub)

寻找子字符串 sub 在 s 中出现的第一个位置,返回索引,未找到返回 -1

s = 'hello world'
print(s.find('l')) # 2

10. s.index(sub)

同 find,但若未找到会引发 ValueError

s = 'hello world'
print(s.index('l')) # 2

11. s.startswith(prefix)

判断 s 是否以 prefix 开头

s = 'hello world' 
print(s.startswith('he')) # True

12. s.endswith(suffix)

判断 s 是否以 suffix 结尾

s = 'hello world'
print(s.endswith('ld')) # True
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值