字符串、字符串方法

1、字符串下标

name = 'world'
print(name)
print(name[1 : 4 : 2])  #ol第一个数字1表示从下表为1的位置开始显示,第二个数字4表示到位置为4的下标结束,第三个数字2表示每2个字母选取一个

2、字符串方法

 ①len()方法:获取字符串长度,有返回值

name = 'helloworld'
length = len(name)
print(length)  #显示结果:10

 ②find():字符串中查找字符,有返回值

name = 'helloworld'
position = name.find('w')
print(position)  #显示结果:5

 ③count()方法:查找字符串中出现的字符的次数

name = 'helloworld'
num = name.count('o')
print(num)  #显示结果:2

 ④in 和 not in :判断字符是否存在于字符串中,有返回值

name = 'helloworld'
print('o' in name)  #显示结果:True
print('o' not in name)  #显示结果:False

⑤replace(' ', ' ')方法:替换字符串中的字符,有返回值

name = 'helloworld'
new_name = name.replace('l', '-' )
print(new_name)  #内容显示:he--owor-d

⑥split()方法:分隔字符串,有返回值,返回值类型为列表list形式

name = 'helloworld'
print(name.split('o'))  #显示结果:['hell', 'w', 'rld']

 

posted @ 2020-12-27 21:00  半世琉璃倾城泪  阅读(81)  评论(0)    收藏  举报