Python之--字符串数据类型常用方法

1.索引

  什么是索引呢,就是在一个字符串中,不管是单个字符还是多个字符,也不管是英文还是中文,在Python3中,每个字符串都是由单个或者多个字符构成,每个字符都有它在字符串中的位置,这个位置就叫字符的索引。举个栗子:

test = 'meng'
print(test[0])    #第一个字符m    
print(test[1])    #第二个字符e
print(test[2])    #第三个字符n
print(test[3])    #第四个字符g

注意:每个索引都是从0开始。

2.切片

  切片就是为了弥补索引的不足,因为索引只能调出一个字符,如果想要调出多个字符就可以使用切片,一次性把需要的字符串切割出来。栗子:

test = 'meng'
print(test[0:3])    #输出men

注意:切片的切割范围是"左闭右开"区间,如上例,3代表的位置是g,而g并没有输出。

3.range

  range表示的是一个数范围,首先range()带三个参数,按顺序分别是起始位置,终止位置,步长。起始位置表示你从哪开始,终止位置是到哪结束,步长表示一次隔多少就算一次。举个栗子:

for i in range(0, 10, 2):
    print(i)
#会输出0 2 4 6 8

4.len

  表示计算一个字符串的长度。也比较容易。

test = 'adfdsfads'
print(len(test))
#随便输入一个字符串,len会计算字符串的长度

5.for

扫描二维码关注公众号,回复: 52056 查看本文章

  表示一个循环,内部自带计数器。栗子:

for i in range(10):
    print(i)
#range(10)表示把0-9这个范围内的数,print打印出来

6.join

  这个比较重点:表示将某个字符串插入到另一个字符串中。

test = 'hello world'
print('*'.join(test))
#结果:h*e*l*l*o* *w*o*r*l*d

7.split

  分割字符串,不会得到以什么分隔的那一个字符串。

test = 'hello world'
print(test.split('o'))
#结果:['hell', ' w', 'rld'],split默认是能分几个算几个,如果要指定分割几个可以在后面加上数字

例如:

test = 'hello world'
print(test.split('o', 1))
#结果:['hell', ' world'],只是分割第一个o

8.upper

  把字符串的字符全变成大写。easy

test = 'hello world'
print(test.upper())
#结果:HELLO WORLD

9.lower

  把字符串全变成小写。不多说

test = 'HELLO WORLD'
print(test.lower())
#结果:hello world

10.find

  查找特定的字符串。如果find没找到就会返回-1,如果找到了返回字符串的位置。

test = 'hello world'
print(test.find('lol'))
#返回-1

11.strip

  用于移除字符串头尾指定的字符(默认为空格)。

str1 = "0000000     meng  0000000"
print(str1.strip('0'))
#结果:     meng  ,注意空格没有被删除

12.replace

  把一个字符串替换成另一个字符串。

var1 = 'hello'
var2 = 'worldddd'
test = 'hello world'
print(test.replace(var1, var2))
#结果:worldddd world

猜你喜欢

转载自www.cnblogs.com/yuxinda00/p/8921551.html