字符串:
需要掌握的操作
#1. strip, lstrip, rstrip
name = '*egon**'
print(name.strip('*'))
print(name.lstrip('*'))
print(name.rstrip('*'))
egon
egon**
*egon
#2. lower, upper
name='eGon'
print(name.lower())
print(name.upper())
egon
EGON
#3. startswith, endswith
name='alex_AB'
print(name.endswith('ab'))
print(name.startswith('alex'))
False
True
#4. format的三种玩法
res1 ='{}{}{}'.format('egon',18,'male')
res2='{1}{0}{1}'.format('egon',18,'male')
res3='{name}{age}{sex}'.format(sex='male',name='egon',age=18)
print(res1,res2,res3)
egon18male 18egon18 egon18male
#5. split, rsplit #默认分隔符是空格
name='root:x:0:0::/root:/bin/bash'
print(name.split(':'))
name='C:/a/b/c/d.txt'
print(name.split('/',2)) ## 等于1时可拿到顶级目录
name='a|b|c'
print(name.rsplit('|',1))
['root', 'x', '0', '0', '', '/root', '/bin/bash'] ##注意::的输出结果
['C:', 'a', 'b/c/d.txt']
['a|b', 'c']
#6 join ##可迭代对象必须是字符串
tag=''
print(tag.join(['egon','say','hello','world']))
egonsayhelloworld
#7 replace ##默认全部替换??
name='alex say: i have one tesla, my name is alex'
print(name.replace('alex','AB',3))
AB say: i have one tesla, my name is AB
#8 isdigit ##可判断bytes和unicode?类型,是最常用的用于判断字符是否为“数字”的方法
age=input('>>: ')
print(age.isdigit())
True or False
其他操作(了解)
#1. find, rfind, index, rindex, count
name='egon say hello'
print(name.find('o',1,3)) ##顾头不顾尾,找不到则返回-1不会报错,找到显示索引
print(name.count('e',1,3)) ##顾头不顾尾,不指定范围查找所有
print(name.index('e',2,4)) ##类似find,但找不到报错
2 ??只能找一个??
0
Traceback (most recent call last):
#2. center, ljust, rjust, zfill
name='egon'
print(name.center(30,'-'))
print(name.ljust(30,'*'))
print(name.rjust(30,'*'))
print(name.zfill(50)) ##用0填充
-------------egon-------------
egon**************************
**************************egon
0000000000000000000000000000000000000000000000egon
#3. expandtabs
name='egon\thello'
print(name)
print('\t')
print(name.expandtabs(0))
print(name.expandtabs(1))
egon hello
egonhello
egon hello
#4. captalize, swapcase, title
msg='egon sAy hi'
print(msg.capitalize()) ##首字母大写
print(msg.swapcase()) ##大小写翻转
print(msg.title()) ##单个单词的首字母大写
Egon say hi
EGON SaY HI
Egon Say Hi
#5. is数字类型
#6. is 其他