python学习笔记1-字符串的使用

字符串运算+和*的例子:
输出一个方框包裹的字符
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函数

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值