|
字符串
Python中字符串相关的处理都非常方便,来看例子:
a = 'Life is short, you need Python'
a.lower() # 'life is short, you need Python'
a.upper() # 'LIFE IS SHORT, YOU NEED PYTHON'
a.count('i') # 2
a.find('e') # 从左向右查找'e',3
a.rfind('need') # 从右向左查找'need',19
a.replace('you', 'I') # 'Life is short, I need Python'
tokens = a.split() # ['Life', 'is', 'short,', 'you', 'need', 'Python']
b = ' '.join(tokens) # 用指定分隔符按顺序把字符串列表组合成新字符串
c = a + '\n' # 加了换行符,注意+用法是字符串作为序列的用法
c.rstrip() # 右侧去除换行符
[x for x in a] # 遍历每个字符并生成由所有字符按顺序构成的列表
'Python' in a # True
Python2.6中引入了format进行字符串格式化,相比在字符串中用%的类似C的方式,更加强大方便:
a = 'I’m like a {} chasing {}.'
# 按顺序格式化字符串,'I’m like a dog chasing cars.'
a.format('dog', 'cars')
# 在大括号中指定参数所在位置
b = 'I prefer {1} {0} to {2} {0}'
b.format('food', 'Chinese', 'American')
# >代表右对齐,>前是要填充的字符,依次输出:
# 000001
# 000019
# 000256
for i in [1, 19, 256]:
print('The index is {:0>6d}'.format(i))
# <代表左对齐,依次输出:
# *---------
# ****------
# *******---
for x in ['*', '****', '*******']:
progress_bar = '{:-<10}'.format(x)
print(progress_bar)
for x in [0.0001, 1e17, 3e-18]:
print('{:.6f}'.format(x)) # 按照小数点后6位的浮点数格式
print('{:.1e}'.format(x)) # 按照小数点后1位的科学记数法格式
print ('{:g}'.format(x)) # 系统自动选择最合适的格式
template = '{name} is {age} years old.'
c = template.format(name='Tom', age=8)) # Tom is 8 years old.
d = template.format(age=7, name='Jerry')# Jerry is 7 years old. |
|