str常用命令:
字符操作:.capitalize() .upper() .lower() .title() .swapcase()
判断:.startwith() .endwith() .isalnum() .isalpha() .isdigit()
统计:.count() len()
索引:.find() .index()
结构:.format() .strip() .lstrip() .rstrip() .split() .replace .center() .expandtabs()
循环:for
1,首字母大写:
s.capitalize()
s1 = 'python is good'
s2 = s1.capitalize()
print(s2)
2,全部大写:
s.upper()
s1 = 'python is good'
s2 = s1.upper()
print(s2)
3,全部小写
s.lower()
s1 = 'Python iS good'
s2 = s1.lower()
print(s2)
result:python is good
4,大小写翻转:
s.swapcase()
s1 = 'Python iS good'
s2 = s1.swapcase()
print(s2)
result:pYTHON Is GOOD
5,每个分隔的单词首字母大写:
s.title()
s1 = 'Python iS good'
s2 = s1.title()
print(s2)
result:Python Is Good
6,字符串居中:
s.center(20)--20代表输出宽度
s1 = 'Python iS good'
s2 = s1.center(20)
print(s2)
s.center(20,'-')--符号代表填充内容
s1 = 'Python iS good'
s2 = s1.center(20,'-')
print(s2)
7,自动填充,当字符串中有 (tab键),前面不足8位的补充到8位,不足16未补充到16位:
s.expandtabs()
8,字符串长度:
len(s)--长度
s1 = 'Python iS good'
s2 = len(s1)
print(s2)
result:14
9,判断字符串以什么开头/结尾:
s.startwith('e',start='',end='')--e表示查找对象,start/end切片定位,返回true/faulse
s1 = 'Python iS good'
s2 = s1.startswith('o')
print(s2)
result:False
s1 = 'Python iS good'
s2 = s1.startswith('P')
print(s2)
result:true
s1 = 'Python iS good'
s2 = s1.startswith('P',2,5)
print(s2)
result:False
s.endwith('')--同理
10.根据元素找索引:
s.find('')--返回元素位置索引,未找到返回-1.
s1 = 'Python iS good'
s2 = s1.find('S')
print(s2)
result:8
s1 = 'Python iS good'
s2 = s1.find('w')
print(s2)
result:-1
s.index('')--同理,未找到报错
s1 = 'Python iS good'
s2 = s1.index('w')
print(s2)
result:ValueError: substring not found
s1 = 'Python iS good'
s2 = s1.index('S')
print(s2)
result:8
11,去掉空格:常用于有用户输入的地方
s.strip()--去掉前后空格
s1 = ' Python iS good '
s2 = s1.strip()
print(s2)
result:Python iS good
s.strip('%')--%表示要去掉的所有元素,可多个元素-%q,也可有空格- %q
s.lstrip()--去掉前端空格
s1 = ' Python iS good '
s2 = s1.lstrip()
print(s2)
result:Python iS good
s.rstrip()--去掉尾部空格
s1 = ' Python iS good '
s2 = s1.rstrip()
print(s2)
result: Python iS good
*strip的坑: