一.字符串方法
1.len用来统计字符串的长度
str1 = 'hello world!'
print len(str1)
2.count用来统计某一子字符串出现的次数
str2 = 'hello hello!'
print str2.count('hello')
3.index和find用来查找指定字符串
print str1.index('wo')
使用index()方法时,如果子字符串不存在,程序会报错
print hello_str.find('he')
如果查找的字符串不存在,返回-1
4.isdigit用来判断字符串是否只含有数字
num_str = '123'
print num_str.isdigit()
5.startswitch用来判断字符串是否以指定的字符串开始
hello_str = 'hello world'
print hello_str.startswith('he')
endswitch用来判断字符串是否以指定的字符串结尾
print hello_str.endswith('ld')
6.replace用来替换指定字符串
print hello_str.replace('world','python')
7.isspace用来判断字符串是否为空
space_str = ' '
print space_str.isspace()
8.字符串中含有中文,在输出字符串时
str1 = 'hell world!'
str2 = u'我的偶像是周杰伦' 在字符串前加u,可消除编码问题
for char in str1:
print char
for word in str2:
print char
二.字符串的切片
num_str = '0123456789'
1.num_str[开始位置:结束位置],包含起始位置,不包含结束位置
print num_str[2:5]
2.结束位置不写,表示到字符串的结尾
print num_str[2:]
3.开始位置不写,表示从字符串的开头开始
print num_str[:10]
4.开始位置和结束位置均不写,表示整个字符串
print num_str[:]
5.指定步长的格式为[开始位置:结束位置:步长]
print num_str[0:10:2]
6.字符串的最后一个字符,可以用结尾的索引值,也可以用-1,倒数第二个用-2,以此类推
print num_str[-1]
7.逆序输出字符串:[-1::-1]第一个-1表示从末尾开始,第二个-1表示步长为向左每次1步,两个冒号中间不写是直到字符串的开始
print num_str[-1::-1]