使用format函数操作字符串

字符串的基本操作

所有标准序列操作(索引、切片、乘法、成员资格检查、长度、最小值、最大值)都适用于字符串,但是字符串是不可变的。

In [16]: website = 'http://www.python.org'

In [17]: website[-3:]='com'
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-17-d8a17dd95ce7> in <module>
----> 1 website[-3:]='com'

TypeError: 'str' object does not support item assignment

设置字符串的格式:精简版

字符串中的%s称为转换说明符,指出了要将值插入什么地方,s意味着将值视为字符串进行格式设置。

In [28]: format = "Hello, %s. %s enough for ya?"

In [29]: values = ('world', 'Hot')

In [30]: format % values
Out[30]: 'Hello, world. Hot enough for ya?'

模板字符串

In [31]: from string import Template

In [32]: tmpl = Template("Hello, $who! $what enough for ya?")

In [33]: tmpl.substitute(who="Mars", what="Dusty")
Out[33]: 'Hello, Mars! Dusty enough for ya?'

编写新代码时,应选择使用字符串方法format,它融合并强化了早期方法的优点,使用这种方法时,每个替换字段都用花括号括起。

# 无索引  按顺序
In [34]: "{}, {} and {}".format("first", "second", "third")
Out[34]: 'first, second and third'

# 有索引 按照索引顺序
In [35]:  "{3} {0} {2} {1} {3} {0}".format("be", "not", "or", "to")
Out[35]: 'to be or not to be'

# 命名字段
In [36]: from math import pi
In [37]:  "{name} is approximately {value:.2f}.".format(value=pi, name="π")
Out[37]: 'π is approximately 3.14.'

# python 3.6中的简写 使用f字符串加载前面
In [39]: f"Euler's constant is roughly {e}."
Out[39]: "Euler's constant is roughly 2.718281828459045."

设置字符串的格式:完整版

这里的基本思想是对字符串调用方法format,并提供要设置其格式的值。字符串包含有关如何设置格式的信息,而这些信息是使用一种微型格式指定语言指定的。
每个值都被插入字符串中,以替换用花括号括起的替换字段。

替换字段名

只需向format提供要设置其格式的未命名参数,并在格式字符串中使用未名名字段。

In [40]: "{foo} {} {bar} {}".format(1, 2, bar=4,foo=3)
Out[40]: '3 1 4 2'

只访问其组成部分

fullname = ["Alfred", "Smoketoomuch"]
In [45]: "Mr {name[1]}".format(name=fullname)
Out[45]: 'Mr Smoketoomuch'


In [46]: import math
IIn [47]: tmpl= "The {mod.__name__} module defines the value {mod.pi} for π"
In [48]: tmpl.format(mod=math)
Out[48]: 'The math module defines the value 3.141592653589793 for π'

基本转换

指定要在字段汇总包含的值后,就可以添加有关如何设置其格式的指令了。

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

还可以指定要转换的值是那种类型,如,你提供一个整数,但是将其作为小数进行处理,为此,可以在格式说明使用字符f(表示定点数)

In [51]: "The number is {num}".format(num=42)
Out[51]: 'The number is 42'


In [52]: "The number is {num:f}".format(num=42)
Out[52]: 'The number is 42.000000'

#将其作为二进制数进行处理
In [55]: "The number is {num:b}".format(num=42)
Out[55]: 'The number is 101010'
类型含 义
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设置格式,再在后面加上%)
宽度、精度和千位分隔符

设置浮点数时。默认在小数点后显示6位小数,并根据需要设置字段长度,而不进行任何形式的填充。

数值和字符串的对齐方式不同:

In [56]: "{num:10}".format(num=3)
Out[56]: '         3'

In [57]: "{num:10}".format(num="Bob")
Out[57]: 'Bob       '

精度也是使用整数指定,但是需要在它前面加上一个表示小数点的据点句点

In [58]: "{pi:.2f}".format(pi=pi)
Out[58]: '3.14'

In [59]: "{pi:.5f}".format(pi=pi)
Out[59]: '3.14159'

使用逗号来指定你要添加的千位分隔符

In [60]: "One googol is {:,}".format(1000000)
Out[60]: 'One googol is 1,000,000'
符号、对齐和用0填充
In [63]: '{:010.2f}'.format(pi)
Out[63]: '0000003.14'

In [64]: '{:020.2f}'.format(pi)
Out[64]: '00000000000000003.14'


# 对齐方式
In [67]: '{0:<20.2f}'.format(pi)
Out[67]: '3.14                '

In [68]: '{0:>20.2f}'.format(pi)
Out[68]: '                3.14'

In [69]: '{0:^20.2f}'.format(pi)
Out[69]: '        3.14        '


# 使用其他字符填充
In [72]: "{:$^16}".format(" WIN ")
Out[72]: '$$$$$ WIN $$$$$$'

In [73]: "{:$^15}".format(" WIN ")
Out[73]: '$$$$$ WIN $$$$$'

# 说明符=,指定将填充字符放在符号和数字之间


字符串方法

center

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

In [21]: "hello".center(39)
Out[21]: '                 hello                 '

In [22]: "hello".center(39,"*")
Out[22]: '*****************hello*****************'

find

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

In [23]: 'With a moo-moo here, and a moo-moo there'.find('moo')
Out[23]: 7

In [24]: 'With a moo-moo here, and a moo-moo there'.find('moo123')
Out[24]: -1

还可以指定起点和终点

>>> subject = '$$$ Get rich now!!! $$$' 
>>> subject.find('$$$') 
0 
>>> subject.find('$$$', 1) # 只指定了起点
20 
>>> subject.find('!!!') 
16 
>>> subject.find('!!!', 0, 16) # 同时指定了起点和终点
-1
join

与split相反,用于合并序列的元素;

In [30]: seq = [1,2,3,4,5]

In [31]: sep='+'

In [32]: sep.join(seq)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-32-5d735a9e9997> in <module>
----> 1 sep.join(seq)

TypeError: sequence item 0: expected str instance, int found

In [33]: seq = ['1','2','3','4','5']

In [34]: sep.join(seq)
Out[34]: '1+2+3+4+5'

合并序列的元素必须是字符串;

lower

返回字符串的小写版本

title

返回大写版本

replace
strip

方法strip将字符串开头和末尾的空白删除,并返回删除后的结果。除此之外还可以指定删除那些字符,但是只能删除开头和结尾的。

translate

和Replace一样替换字符串的特定部分,但不同的是它只能进行单字符替换,优势在于能够同时替换多个字符,比replace效率高。

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

可以使用以下方法:
isalnum、isalpha、isdecimal、isdigit、isidentifier、islower、isnumeric、
isprintable、isspace、istitle、isupper

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值