Python格式化字符串

本文介绍了Python中字符串格式化的两种方法:使用string模块的Template对象及str.format()函数,并展示了位置参数、关键字参数等应用实例。此外还列举了常用的字符串内建函数,如大小写转换、对齐填充等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在Python中可以使用string模块中的字符串模板(Template)对象进行字符串的格式化

>>> from string import Template

>>> s = Template('There are ${howmany} ${lang} Quotation Symbols')
>>>
>>> print s.substitute(lang='Python', howmany=3)
There are 3 Python Quotation Symbols
>>>
>>> print s.substitute(lang='Python')#出错,错误信息已删除
>>>
>>> print s.safe_substitute(lang='Python')

There are ${howmany} Python Quotation Symbols


以下转载自:http://www.cnblogs.com/wilber2013/p/4641616.html

Python2.6开始,新增了一种格式化字符串的函数str.format(),通过这个函数同样可以对字符串进行格式化处理。在format()函数中,使用“{}”符号来当作格式化操作符。

# 位置参数
print "{0} is {1} years old".format("Wilber", 28)
print "{} is {} years old".format("Wilber", 28)
print "Hi, {0}! {0} is {1} years old".format("Wilber", 28)

# 关键字参数
print "{name} is {age} years old".format(name = "Wilber", age = 28)

# 下标参数
li = ["Wilber", 28]
print "{0[0]} is {0[1]} years old".format(li)

# 填充与对齐
# ^、<、>分别是居中、左对齐、右对齐,后面带宽度
# :号后面带填充的字符,只能是一个字符,不指定的话默认是用空格填充
print '{:>8}'.format('3.14')
print '{:<8}'.format('3.14')
print '{:^8}'.format('3.14')
print '{:0>8}'.format('3.14')
print '{:a>8}'.format('3.14')

# 浮点数精度
print '{:.4f}'.format(3.1415926)
print '{:0>10.4f}'.format(3.1415926)

# 进制
# b、d、o、x分别是二进制、十进制、八进制、十六进制
print '{:b}'.format(11)
print '{:d}'.format(11)
print '{:o}'.format(11)
print '{:x}'.format(11)
print '{:#x}'.format(11)
print '{:#X}'.format(11)

# 千位分隔符
print '{:,}'.format(15700000000)

下面整理出来了一些常用的str类型的内建函数:

# 小写 
S.lower() 
# 大写 
S.upper() 
#大小写互换 
S.swapcase() 
# 首字母大写 
S.capitalize() 

# 输出width个字符,S左对齐,不足部分用fillchar填充,默认的为空格。 
S.ljust(width,[fillchar]) 
# 右对齐 
S.rjust(width,[fillchar]) 
# 中间对齐 
S.center(width, [fillchar]) 

# 返回S中出现substr的第一个字母的标号,如果S中没有substr则返回-1。start和end作用就相当于在S[start:end]中搜索 
S.find(substr, [start, [end]]) 
# 返回S中最后出现的substr的第一个字母的标号,如果S中没有substr则返回-1,也就是说从右边算起的第一次出现的substr的首字母标号 
S.rfind(substr, [start, [end]]) 
# 计算substr在S中出现的次数 
S.count(substr, [start, [end]]) 
#把S中的oldstar替换为newstr,count为替换次数
S.replace(oldstr, newstr, [count]) 

# 把S中前后chars中有的字符全部去掉,可以理解为把S前后chars替换为None 
S.strip([chars]) 
S.lstrip([chars]) 
S.rstrip([chars]) 

# 以sep为分隔符,把S分成一个list。maxsplit表示分割的次数。默认的分割符为空白字符 
S.split([sep, [maxsplit]]) 
# 把seq代表的字符串序列,用S连接起来 
S.join(seq)


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值