字符串切片
需要要到下标,下标从零开始
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