Python学习笔记:使用字符串
使用字符串
使用字符串格式:精简版
- 百分号 %
# 指定要设置其格式的值时,可使用单个值(如字符串或数字),可使用元组(如果要设置多个值得格式),还可使用字典
>>> format = "Hello, %s. %s enough for ya?"
>>> values = ('world', 'Hot')
>>> format % values
'Hello, world. Hot enough for ya?'
- 类似UNIX shell的语法
>>> from string import Template
>>> tmpl = Template("Hello, $who! $what enough for ya?")
>>> tmpl.substitute(who="Mars", what="Dusty")
'Hello, Mars! Dusty enough for ya?'
- format
>>> "{}, {} and {}".format("first", "second", "third")
'first, second and third'
>>> "{0}, {1} and {2}".format("first", "second", "third")
'first, second and third'
命名字段
>>> from math import pi
>>> "{name} is approximately {value:.2f}.".format(value=pi, name="π")
'π is approximately 3.14.'
如果变量与替换字段同名,还可使用一种简写:f字符串
>>> from math import e
>>> f"Euler's constant is roughly {e}."
"Euler's constant is roughly 2.718281828459045."
使用字符串格式:完整版
- 替换字段名
按顺序将字段和参数配对;还可给参数指定名称
>>> "{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
>>> tmpl = "The {mod.__name__} module defines the value {mod.pi} for π"
>>> tmpl.format(mod=math)
'The math module defines the value 3.141592653589793 for π'
- 转换标志
s代表str,r代表repr,a代表ascii
>>> print("{pi!s} {pi!r} {pi!a}".format(pi="π"))
π 'π' '\u03c0'
字符串格式设置中的类型说明符
类型 | 含义 |
---|---|
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设置格式,再在后面加上%) |
- 宽度、精度和千位分隔符
宽度使用整数指定
>>> "{num:10}".format(num=3)
' 3'
>>> "{name:10}".format(name="Bob")
'Bob '
精度也是使用整数指定的
>>> "Pi day is {pi:.2f}".format(pi=pi)
'Pi day is 3.14'
可同时指定宽度和精度
>>> "{pi:10.2f}".format(pi=pi)
' 3.14'
使用都好来指出千位分隔符
>>> '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'
同时指定其他格式设置元素时,这个逗号应放在宽度和表示精度的句点之间。
- 符号、对齐和使用0填充
在指定宽度和精度的数前面,可添加一个标志
>>> '{:010.2f}'.format(pi)
'0000003.14'
要指定左对齐、右对齐和居中,可分别使用<、>和^。
>>> print('{0:<10.2f}\n{0:^10.2f}\n{0:>10.2f}'.format(pi))
3.14 3.14 3.14
还有更具体的说明符=,它指定将填充字符放在符号和数字之间。
>>> 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:-.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
井号(#)选项
# 对于二进制、八进制和十六进制转换,将加上一个前缀
>>> "{:b}".format(42)
'101010'
>>> "{:#b}".format(42)
'0b101010'
# 对于各种十进制数,它要求必须包含小数点(对于类型g,它保留小数点后面的零)。
>>> "{:g}".format(42)
'42'
>>> "{:#g}".format(42)
'42.0000'
字符串方法
- center 通过在两边添加填充字符(默认为空格)让字符串居中 ljust、rjust、zfill
- find 在字符串中查找子串。如果找到,就返回子串的第一个字符的索引,否则返回-1。 rfind、index、rindex、count、startswith、endswith
- join 用于合并序列的元素 split
- lower 返回字符串的小写版本 islower、istitle、isupper、translate、capitalize、casefold、swapcase、title、upper
# title 词首大写
>>> "that's all folks".title()
"That'S All, Folks"
# 另一种方法是使用模块string中的函数capwords。
>>> import string
>>> string.capwords("that's all, folks")
That's All, Folks"
- replace 替换 translate、expandtabs
- split 与join相反,用于将字符串拆分为序列 join、partition、rpartition、rsplit、splitlines
- strip 将字符串开头和末尾的空白(但不包括中间的空白)删除,并返回删除后的结果 lstrip、rstrip
- translate 进行单字符替换 replace、lower
# str.maketrans 创建转换表
>>> table = str.maketrans('cs', 'kz')
>>> table
{115: 122, 99: 107}
# 转换
>>> 'this is an incredible test'.translate(table)
'thiz iz an inkredible tezt'
# maketrans 第三个参数,指定要将哪些字母删除
>>> table = str.maketrans('cs', 'kz', ' ')
>>> 'this is an incredible test'.translate(table)
'thizizaninkredibletezt'
- 判断字符串是否满足特定的条件:如isspace、isdigit和isupper 表示包含的字符全为空白、数字或大写。isalnum、isalpha、isdecimal、isdigit、isidentifier、islower、isnumeric、isprintable、isspace、istitle、isupper。
小结
字符串格式设置:求模运算符(%)可用于将值合并为包含转换标志(如%s)的字符串,这让你能够以众多方式设置值的格式,如左对齐或右对齐,指定字段宽度和精度,添加符号(正号或负号)以及在左边填充0等。
字符串方法:字符串有很多方法,有些很有用(如split和join),有些很少用到(如istitle和capitalize)。