Python数据类型:
字符串
字符串基本操作
eg: 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 一共出现几个 i
a.find(‘e’) # 从左向右查找’e’,3
a.rfind(‘need’) # 从右向左查找’need’,19
a.replace(‘you’, ‘I’) # ‘Life is short, I need Python’ 替换you成I
tokens = a.split() # [‘Life’, ‘is’, ‘short,’, ‘you’, ‘need’, ‘Python’] 用空格分开
b = ’ —’.join(tokens) # 用指定分隔符把字符串列表组合成新字符串,
#Life—is—short,—you—need—Python
c = a + ‘\n’ # 加了换行符,注意+用法是字符串作为序列的用法 a是通过split()以空格分开的,现在在每一个分开的单词中间加上回车
c.rstrip() # 右侧去除换行符 去除最右边的一个回车
[x for x in a] # 遍历每个字符并生成由所有字符按顺序构成的列表
‘Python’ in a # True 判断该单词在不在a中
字符串格式化
a = ‘I’m like a {} chasing {}.’
a.format(‘dog’, ‘cars’) # 按顺序格式化字符串,‘I’m like a dog chasing cars.’
b = ‘I prefer {1} {0} to {2} {0}’
b.format(‘food’, ‘Chinese’, ‘American’) # 在大括号中指定参数所在位置
‘>’代表右对齐,>前是要填充的字符,依次输出:
for i in [1, 19, 256]:
print(‘The index is {:0>6d}’.format(i))
结果
000001
000019
000256
’<‘代表左对齐,依次输出:
for x in [’’, '’, '****’]:
progress_bar = ‘{:-<10}’.format(x)
print(progress_bar)
*---------
****------
*******—
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.