Python 字符串常用操作

字符串切片

需要要到下标,下标从零开始
String[起始步骤:结尾(不包含结束未本身):步长]

string = 'hellow csdn '
string[1:]

反转字符串string[::-1]

string[::-1]

查找字符串下标 find() index()

string = 'hellow csdn'
# find()
string.find('h')
# rfind()
string.rfind('h')
# index()
string.index('h')

find(‘字符串’,start=开始匹配的下标,end=结尾)
find和index的区别 index找不到会报错,find找不到返回-1
find和rfind的区别 find从左边开始查找,rfind从右边开始查找

查找元素在字符中出现的个数count()

string = 'hellow csdn'
print(string.count('h'))

去字符串两边的空格strip()

string = '   hellow csdn   '
print(string.strip())  # hellow csdn

替换字符串中的元素replace()

string = 'hellow csdn'
print(string.replace('o', 's')) # hellsw csdn  

分割字符串split()

string = 'hellow CSDN 你好 CSDN'
print(string.split(' ')) # ['hellow', 'CSDN', '你好', 'CSDN']
print(string.split(' ', 2)) # ['hellow', 'CSDN', '你好 CSDN']

查找字符串以什么开头startswith()

返回结果为True\False

string = 'hellow CSDN'
print(string.startswith('hellow')) # True
print(string.startswith('CSDN')) # False

以什么结尾endswitch()

返回结果为True\False

string = 'hellow CSDN'
print(string.endswith('hellow')) # Fales
print(string.endswtich('CSDN')) # True

大小写转换upper() lower()

string = 'hellow CSDN'
# upper()大写转换
print(string.upper()) # HELLOW CSDN

# lower()小写转换
print(string.lower()) # hellow csdn

将每个单词的首字母大写title()

string = 'hellow csdn'
print(string.title()) # Hellow Csdn

字符串的第一个字母大写capitalize()

string = 'hellow csdn'
print(string.capitalize()) # Hellow csdn

拼接字符串join()

s= '_'
string = ['hellow', 'csdn']
print(s.join(string)) # hellow_csdn
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值