字符串运算+和*的例子:
输出一个方框包裹的字符
sentence = input("sentence:")
screen_width = 80
text_width = len(sentence)
box_width = text_width
left_margin = (screen_width-box_width)//2
print(" "*left_margin+"+"+"-"*box_width + "+")
print(" "*left_margin+"|"+" "*text_width + "|")
print(" "*left_margin+"|"+ sentence + "|")
print(" "*left_margin+"|"+" "*text_width + "|")
print(" "*left_margin+"+"+"-"*box_width + "+")
结果:
========================= RESTART: F:/python3/方框.py =========================
sentence:hellodsasdasdsdas
+-----------------+
| |
|hellodsasdasdsdas|
| |
+-----------------+
字符串格式化
字符串格式化可以使用格式化操作符"%"来实现
例子:
format = 'hellow %s %s enough for ya?'
values = ('world','hot')
print(format%values)
结果:
hellow world hot enough for ya?
格式化浮点数
例子:
format = 'π保留三位小数是:%.3f'
from math import pi
print(format%pi)
结果:
π保留三位小数是:3.142
使用模板字符串来实现
例子;
from string import Template
s = Template('$x.glorious $x!x')
s.substituted(x="slurm")
结果:
'slurm.glorious slurm!x'
例子:
s = Template('it is ${x}tastic')
s.substitute(x='slurm')
结果:
'it is slurmtastic'
字符串操作:
find:
find方法返回子字符串在字符串中的最左端索引
例子:
titl = 'hellow python'
titl.find('hellow')
结果:
0
join:
split方法的逆方法,用来在队列中添加元素(需要添加的元素必须是字符串)
例子:
>>> seq=['1','2','3','4','5']
>>> sep='+'
>>> sep.join(seq)
结果:
'1+2+3+4+5'
lower:
返回字符串的小写字母版(可以用在编写不区分大小写的代码)
例子:
>>>'Hello World'.lower()
'hello world'
replace:
返回某字符串的所有匹配项均被替换之后得到的字符串
例子:
>>>'hellow world'.replace('world','boy')
'hellow boy'
split:
join的逆方法,用来将字符串分割成序列
例子:
>>> '1+2+3+4+5'.split('+')
['1', '2', '3', '4', '5']
如果不提供任何分隔符,程序会把所有空格当做分隔符
strip:
方法返回去除两侧空格的字符串
例子:
>>> ' hellow '.strip()
'hellow'
translate:
方法和replace一样,可以替换字符串的某些部分,但是只能处理单个字符,但是可以同时进行多个替换
使用translate之前,需要完成一张转换表,可以使用string模块里面的maketrans函数
python学习笔记1-字符串的使用
最新推荐文章于 2022-06-07 11:17:48 发布