python如何正确的操作字符串
0x01 字符串(string)
字符串是 python 中最常用的数据类型,同时支持单引号和双引号。使用双引号时打印字符串时用单引号。
>>> "hello world!" 'hello world!' >>> 'hello world!' 'hello world!' >>> "let's go!" "let's go!" >>> 'she said "hello world!" ' 'she said "hello, world!" '
引号转义
上述示例可使用反斜杠(\)对引号进行转义。
>>> 'let\'s go!' "let's go!" >>> "\"hello, world!\" she said" '"hello, world!" she said'
拼接字符串
通常使用 +号拼接字符串,像数字相加一样。
>>> "she said " + '"hello world!"' 'she said "hello world!"' >>> a = "she said " >>> b = '"hello world!"' >>> a + b 'she said "hello world!"'
依次输入两个字符串时,也可实现字符串拼接。
>>> "she said " '"hello world!"' 'she said "hello world!"' # 只有输入的是字符串才有用 >>> a = "she said " >>> b = '"hello world!"' >>> a b file "<stdin>", line 1 a b ^ syntaxerror: invalid syntax
长字符串
可使用三引号表示很长的字符串(跨越多行的字符串)。
>>> """like this""" 'like this' >>> print('''long long ago! "hello world!" she said.''') long long ago! "hello world!" she said.
常规字符串也可横跨多行。只要在行尾加上反斜杠,反斜杠和换行符将被转义,即被忽略。
>>> 1 + 2 + \ 4 + 5 12 >>> print("hello \ world!") hello world! >>> print \ ('hello world') hello world
索引( indexing)
对于字符串字面量,可直接对其执行索引操作,无需先将其赋给变量。
>>> 'hello'[1] 'e'
如果函数调用返回一个序列,可直接对其执行索引操作。
>>> yearnum = input('please input year: ')[3] please input year: 2021 >>> yearnum '1'
将序列与数字n相乘时,将重复这个序列n次来创建一个新序列。
>>> 'python' * 3 'pythonpythonpython'
运算符in
要检查特定的值是否包含在序列中,可使用运算符in
>>> access_mode = 'rw+' >>> 'w' in access_mode true >>> 'x' in access_mode false >>> subject = '$$$ get rich now!!! $$$' >>> '$$$' in subject true
创建列表
使用函数list ,可以快速将字符串转换成一个字符列表。
>>> somelist = list('hello') >>> somelist ['h', 'e', 'l', 'l', 'o']
将字符列表转换为字符串。
>>>''.join(somelist)
切片赋值
>>> name = list('perl') >>> name ['p', 'e', 'r', 'l'] >>> name[2:] = list('ar') >>> name ['p', 'e', 'a', 'r'] >>> name = list('perl') >>> name[1:] = list('ython') >>> name ['p', 'y', 't', 'h', 'o', 'n']
0x02 字符串格式化
格式字符串中的%s称为转换说明符,指出了要将值插入什么地方 并在右边指定要设置其格式的值。指定要设置其格式的值时,可使用单个值(如字符串或数字),可使用元组(如果要设置多个值的格式),还可使用字典,其中最常见的是元组。
>>> format = "hello, %s. %s !" >>> values = ('world', 'python') >>> format % values 'hello, world. python !'
模板字符串
包含等号的参数称为关键字参数,
>>> from string import template >>> tmpl = template("hello, $param1! $param2 !") >>> tmpl.substitute(param1="world", param2="python") 'hello, world! python !'
字符串方法format
>>> "{}, {} and {}".format("first", "second", "third") 'first, second and third' >>> "{0}, {1} and {2}".format("first", "second", "third") 'first, second and third' >>> "{3} {0} {2} {1} {3} {0}".format("be", "not", "or", "to") 'to be or not to be' >>> from math import pi >>> "{name} 约等于 {value:.2f}.".format(value=pi, name="π") 'π 约等于 3.14.''
如果变量与替换字段同名,还可使用一种简写。在这种情况下,使用f字符串——在字符串前面加上f。(python 3.6+)
>>> from math import e >>> f"euler's constant is roughly {e}." # 等价于 "euler's constant is roughly {e}.".format(e=e) "euler's constant is roughly 2.718281828459045."
0x03 如何设置格式
字符串包含有关如何设置格式的信息, 而这些信息是使用一种微型格式指定语言 (mini-language)指定的。每个值都被插入字符串中,以替换用花括号括起的替换字段。 替换字段由如下部分组成,其中每个部分 都是可选的。
- 字段名:索引或标识符,指出要设置哪个值的格式并使用结果来替换该字段。除指定值 外,还可指定值的特定部分,如列表的元素。
- 转换标志:跟在叹号后面的单个字符。当前支持的字符包括r(表示repr)、s(表示str) 和a(表示ascii)。如果你指定了转换标志,将不使用对象本身的格式设置机制,而是使 用指定的函数将对象转换为字符串,再做进一步的格式设置。
- 格式说明符:跟在冒号后面的表达式(这种表达式是使用微型格式指定语言表示的)。格 式说明符让我们能够详细地指定最终的格式,包括格式类型(如字符串、浮点数或十六 进制数),字段宽度和数的精度,如何显示符号和千位分隔符,以及各种对齐和填充方式。
字段名
只需向format提供要设置其格式的未命名参数,并在格式字符串中使用 未命名字段。此时,将按顺序将字段和参数配对。你还可给参数指定名称,这种参数将被用于相 应的替换字段中。你可混合使用这两种方法。
>>> "{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 >>> 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、r和a)指定分别使用str、repr和ascii进行转换。函数str通常创建外观 普通的字符串版本\。函数repr尝试创建给定值的python表 示(这里是一个字符串字面量)。函数ascii创建只包含ascii字符的表示。
>>> print("{pi!s} {pi!r} {pi!a}".format(pi="π")) π 'π' '\u03c0'
格式说明
(即冒号后面)使用字符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'
0x04 字符串方法
常量
模块string中几个很有用的常量
- string.digits:包含数字0~9的字符串。
- string.ascii_letters:包含所有ascii字母(大写和小写)的字符串。
- string.ascii_lowercase:包含所有小写ascii字母的字符串。
- string.printable:包含所有可打印的ascii字符的字符串。
- string.punctuation:包含所有ascii标点字符的字符串。
- string.ascii_uppercase:包含所有大写ascii字母的字符串。
填充方法
字符串填充字符方法
center、 ljust、 rjust、 zfill
split
如果没有指定分隔符,将默认在单个或多个连续的空白字符(空格、制表符、换行符 等)处进行拆分
>>> seq = ['1', '2', '3', '4', '5'] >>> sep = '+' >>> sep.join('+') # 合并一个字符串列表 '1+2+3+4+5' >>> '1+2+3+4+5'.split('+') ['1', '2', '3', '4', '5'] >>> 'using the default'.split() ['using', 'the', 'default']
以上就是python如何正确的操作字符串的详细内容,更多关于python 操作字符串的资料请关注其它相关文章!