附1:格式化字符串(完整版)

替换字段:在格式化字符串中被花括号括起来的为替换字段,要在最终结果中包含花括号,可在格式字符串中使用两个花括号(即{{或}})来指定。

例如:{{和}}经过format函数处理后将留下{和};
           而如果直接使用{和},经过format函数处理后,由于{}之间不是有效的替换字段,所以将会报错

>>>"{{ceci n'est pas une replacement field}}".format()
"{ceci n'est pas une replacement field}"
>>>"{ceci n'est pas une replacement field}".format()
Traceback (most recent call last):
  File "<input>", line 1, in <module>
KeyError: "ceci n'est pas une replacement field"

可选的替换字段:

1)字段名

不能同时使用手工编号和自动编号,因为这样很快会变得混乱不堪。

>>>"{foo} {} {bar} {}".format(1, 2, bar=4, foo=3)
'3 1 4 2'
>>>"{foo} {1} {bar} {0}".format(1, 2, bar=4, foo=3)
'3 2 4 1'
>>>fullname = ["Alfred", "Smoketoomuch"]
>>>"Mr {name[1]}".format(name=fullname)
'Mr Smoketoomuch'
>>>import math
>>>tmp1 = "The {mod.__name__} module defines the value {mod.pi} for π"
>>>tmp1.format(mod=math)
'The math module defines the value 3.141592653589793 for π'

综上,可以看出并非只能使用提供的值本身,还可访问提供的值的组成部分;

替换字段名可以使用索引、标识符,还可使用句点表示法来访问导入的模块中的方法、属性、变量和函数;

2)转换标志

s:即str,通常创建外观普通的字符串版本(这里没有对输入字符串做任何处理);

r:即repr,尝试创建给定值的Python表示(这里是一个字符串字面量);

a:即ascii,创建只包含ASCII字符的表示;

>>>print("{pi!s} {pi!r} {pi!a}".format(pi="π"))
π 'π' '\u03c0'

3)格式说明符

1)格式类型

字符串格式设置中的类型说明符
类型含义
b将整数表示为二进制数
c将整数解读为Unicode码点
d将整数视为十进制数进行处理,这是整数默认使用的说明符
e使用科学表示法来表示小数(用e来表示指数)
E与e相同,但使用E来表示指数
f将小数表示为定点数
F与f相同,但对于特殊值(nan和inf),使用大写表示
g自动在定点表示法和科学表示法之间做出选择。这是默认用于小数的说明符,但在默认情况下至少有1位小数
G与g相同,但使用大写来表示指数和特殊值
n与g相同,但插入随区域而异的数字分隔符
o将整数表示为八进制数
s保持字符串的格式不变,这是默认用于字符串的说明符
x将整数表示为十六进制数并使用小写字母
X与x相同,但使用大写字母
%将数表示为百分比值(乘以100,按说明符f设置格式,再在后面加上%)

例如:

>>>"The number is {num}".format(num=42)
'The number is 42'
>>>"The number is {num:f}".format(num=42)
'The number is 42.000000'
>>>"The number is {num:b}".format(num=42)
'The number is 101010'

2)字段宽度

>>>"{num:10}".format(num=3)
'         3'
>>>"{num:10}".format(num="Bob")
'Bob       '

容易看出,数和字符串的对齐方式不同。

3)数的精度

>>>from math import pi
>>>"Pi day is {pi:.2f}".format(pi=pi)
'Pi day is 3.14'

>>>"{pi:10.2f}".format(pi=pi)
'      3.14'

注意:对于浮点数,.2和.2f的区别

>>>"{pi:.2f}".format(pi=pi)
'3.14'
>>>"{pi:.2}".format(pi=pi)
'3.1'

 对于字符串设置精度,若精度<字符串长度则对齐进行截断;若精度>=字符串长度则不变;

>>>"{:.5}".format("Guido van Rossum")
'Guido'
>>>"{:.50}".format("Guido van Rossum")
'Guido van Rossum'

4)千位分隔符

可使用逗号来指出要添加千位分隔符;

>>>'One googol is {:,}'.format(10**100)
'One googol is 10,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000'

 同时指定其他格式设置元素时,这个逗号应该放在宽度和表示精度的句点之间;

>>>'{:20,.2f}'.format(10**10)
'   10,000,000,000.00'

5)符号

符号放在对齐说明符后面:

       '-':(默认)正数不显示符号;负数显示负号;
       '+':正数显示正号;负数显示负号;
       ' '(空格):正数显示空格;负数显示负号;

如果要给正数加上符号,可使用说明符+(将其放在对齐说明符后面),而不是默认的-。如果将符号说明符指定为空格,会在正数前面加上空格而不是+。

>>>print('{0:-.2}\n{1:-.2}'.format(pi, -pi))#默认设置
3.1
-3.1
>>>print('{0:+.2}\n{1:+.2}'.format(pi, -pi))
+3.1
-3.1
>>>print('{0: .2}\n{1: .2}'.format(pi, -pi))
 3.1
-3.1

6)对齐

>>>print('{0:<10.2f}\n{0:^10.2f}\n{0:>10.2f}\n'.format(pi))
3.14      
   3.14   
      3.14

7)填充

0填充

>>>'{:010.2f}'.format(pi)
'0000003.14'

指定字符填充

>>>'{:$^15}'.format("WIN BIG")
'$$$$WIN BIG$$$$'

8)特殊

=:它指定将填充字符放在符号和数字之间

>>>print('{0:10.2f}\n{1:10.2f}'.format(pi, -pi))
      3.14
     -3.14
>>>print('{0:=10.2f}\n{1:=10.2f}'.format(pi, -pi))
      3.14
-     3.14
>>>print('{0:=010.2f}\n{1:=010.2f}'.format(pi, -pi))
0000003.14
-000003.14

#:将其放在符号说明符和宽度之间(如果指定了这两种设置)。

这个选项将触发另一种转换方式,转换细节随类型而异。例如:对于二进制,八进制和十六进制转换,将加上一个前缀;对于各种十进制数,它要求必须包含小数点(对于类型g,它保留小数点后面的零)

>>>"{:b}".format(42)
'101010'
>>>"{:#b}".format(42)
'0b101010'
>>>"{:g}".format(42)
'42'
>>>"{:#g}".format(42)
'42.0000'

代码清单3-1 字符串格式设置示例

# Print a formatted price list with a given width

width = int(input('Please enter width: '))

price_width = 10
item_width  = width - price_width

header_fmt = '{{:{}}}{{:>{}}}'.format(item_width, price_width)
fmt        = '{{:{}}}{{:>{}.2f}}'.format(item_width, price_width)

print('=' * width)

print(header_fmt.format('Item', 'Price'))

print('-' * width)

print(fmt.format('Apples', 0.4))
print(fmt.format('Pears', 0.5))
print(fmt.format('Cantaloupes', 1.92))
print(fmt.format('Dried Apricots (16 oz.)', 8))
print(fmt.format('Prunes (4 lbs.)', 12))

print('=' * width)

以输入35为例:

>>>print(header_fmt)
{:25}{:>10}
>>>print(fmt)
{:25}{:>10.2f}

3.4 字符串方法

1. 模块string中几个很常用的常量。

>>>import string
>>>string.digits
'0123456789'
>>>string.ascii_letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>>string.ascii_lowercase
'abcdefghijklmnopqrstuvwxyz'
>>>string.ascii_uppercase
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>>string.printable   #包含所有可打印的ASCII字符的字符串
'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c'
>>>string.punctuation   #包含所有ASCII标点字符的字符串
'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'

2. center

通过在两边添加填充字符(默认为空格)让字符串居中

>>>"The Middle by Jimmy Eat World".center(39)
'     The Middle by Jimmy Eat World     '
>>>"The Middle by Jimmy Eat World".center(39, "*")
'*****The Middle by Jimmy Eat World*****'

3. find

在字符串中查找子串。如果找到,就返回子串的第一个字符的索引,否则返回-1。

一个参数为:key,参照范围为整个字符串;

两个参数为:key,start,查找范围为 字符串的start位置到字符串尾;

三个参数为:key,start,end,查找范围为 字符串的[start, end)位置;

>>>"With a moo-moo here, and a moo-moo there".find('moo')
7

>>>title = "Monty Python's Flying Circus"
>>>title.find('Monty')
0
>>>title.find('Python')
6
>>>title.find('Flying')
15
>>>title.find('Zirquss')
-1

>>>subject = '$$$ Get rich now!!! $$$'
>>>subject.find('$$$')
0
>>>subject.find('$$$', 1)
20
>>>subject.find('!!!')
16
>>>subject.find('!!!', 0, 16)
-1

4. join

所合并序列(列表、元组)的元素必须是字符串

>>>seq = [1, 2, 3, 4, 5]
>>>sep = '+'
>>>sep.join(seq)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: sequence item 0: expected str instance, int found

>>>seq = ['1', '2', '3', '4', '5']
>>>sep.join(seq)
'1+2+3+4+5'

>>>dirs = '', 'usr', 'bin', 'env'
>>>'/'.join(dirs)
'/usr/bin/env'

>>>print('C:' + '\\'.join(dirs))
C:\usr\bin\env

5. lower

返回字符串的小写版本

>>>"Trondheim Hammer Dance".lower()
'trondheim hammer dance'
>>>if 'Gumby' in ['gumby', 'smith', 'jones']: print('Found it!')
...

>>>name = 'Gumby'
>>>names = ['gumby', 'smith', 'jones']
>>>if name.lower() in names: print('Found it!')
...
Found it!

6. replace

替换子串

>>>'This is a test'.replace('is', 'eez')
'Theez eez a test'

7. split

作用与join相反,用于将字符串拆分为序列;默认在单个或多个连续的空白字符(空格、制表符、换行符等)处进行拆分;

>>>'1+2+3+4+5'.split('+')
['1', '2', '3', '4', '5']
>>>'/usr/bin/env'.split('/')
['', 'usr', 'bin', 'env']
>>>'Using the default'.split()
['Using', 'the', 'default']

8. strip

删除字符串开头和末尾的空白

>>>'   internal whitespace is kept   '.strip()
'internal whitespace is kept'
>>>names = ['gumby', 'smith', 'jones']
>>>name = 'gumby '
>>>if name in names: print('Found it!')
...
>>>if name.strip() in names: print('Found it!')
...
Found it!

删除指定的某些字符

>>>'*** SPAM * for * everyone!!! ***'.strip(' *!')
'SPAM * for * everyone'

9. translate

第一个参数是要被替换的字符;

第二个参数是要替换成的字符;

第三个参数是要删除的字符;

table = str.maketrans('cs', 'kz', ' ')   将c替换成k,将s替换成z,将空格删除;

#创建转换表
>>>table = str.maketrans('cs', 'kz')
#查看转换表内容,即Unicode码点之间的映射
>>>table
{99: 107, 115: 122}
>>>'this is an incredible test'.translate(table)
'thiz iz an inkredible tezt'

>>>table = str.maketrans('cs', 'kz', ' ')
>>>table
{99: 107, 115: 122, 32: None}
>>>'this is an incredible test'.translate(table)
'thizizaninkredibletezt'

10. 判断字符串是否满足特定的条件

isalnum
isalpha
isdecimal
isdigit
isidentifier
islower
isnumeric
isprintable
isspace
istitle
isupper

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

MallocLu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值