1、我们可以用单引号(‘)或双引号(” ")创建字符串,并为字符串分配一个变量,例如:
1 name = "张三" 2 name = "wangsan"
字符串常用功能:
移除空白、分割、长度、索引、切片、格式化输出
移除空白
strip()函数,只能移除字符串左右两边的空白,字符串中间的空白不能移除
name = " wang san " print(name.strip()) 运行结果:wang san
分割
split(参数)函数,参数:分割节点
1 name = "wang san" 2 str = "my name is lili" 3 print(name.split(" ")) 4 str = str.split('is') 5 print(str) 6 print(str[0]) 7 运行结果: ['wang', 'san'] ['my name ', ' lili'] my name
长度
len('参数')参数:字符串
1 name=wang 2 print(len(name)) 运行结果:4
索引
index(参数),参数:字符串中的字符,查找字符串中某个字符的位置,如
1 str = "my name is lili" 2 print(str.index('n')) 运行结果:3
1 str = "my name is lili" 2 print(str.index(' ')) 运行结果:2 注意:只检索第一个字符
切片
1 str = 'hello world!' 2 print(str[0:5]) 3 print(str[:5]) 4 print(str[:5:2]) 5 print(str[5:])
运行结果:
hello
hello
hlo
world!
字符串相关函数
capitalize()首字母大写
casefold()字母全部小写
center(20,"-")居中,并显示20个字符,不足位置用’-‘填充
count("参数")统计参数的个数
endswith("ie")是否以’ie‘结尾,返回True或者False
find("参数")查找参数并返回个数
1 format : 2 >>> msg = "my name is {}, and age is {}" 3 >>> msg.format("alex",22) 4 'my name is alex, and age is 22' 5 >>> msg = "my name is {1}, and age is {0}" 6 >>> msg.format("alex",22) 7 'my name is 22, and age is alex' 8 >>> msg = "my name is {name}, and age is {age}" 9 >>> msg.format(age=22,name="ale") 10 'my name is ale, and age is 22'