Python 官方文档:入门教程 => 点击学习
目录0x01 字符串(string)引号转义拼接字符串长字符串索引( indexing)运算符in创建列表切片赋值0x02 字符串格式化模板字符串字符串方法fORMat0x03 如何设置
字符串是 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
对于字符串字面量,可直接对其执行索引操作,无需先将其赋给变量。
>>> 'Hello'[1]
'e'
如果函数调用返回一个序列,可直接对其执行索引操作。
>>> yearnum = input('please input year: ')[3]
please input year: 2021
>>> yearnum
'1'
将序列与数字n相乘时,将重复这个序列n次来创建一个新序列。
>>> 'Python' * 3
'pythonpythonpython'
要检查特定的值是否包含在序列中,可使用运算符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']
格式字符串中的%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 !'
>>> "{}, {} 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."
字符串包含有关如何设置格式的信息, 而这些信息是使用一种微型格式指定语言 (mini-language)指定的。每个值都被插入字符串中,以替换用花括号括起的替换字段。 替换字段由如下部分组成,其中每个部分 都是可选的。
只需向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'
模块string中几个很有用的常量
字符串填充字符方法
center、 ljust、 rjust、 zfill
如果没有指定分隔符,将默认在单个或多个连续的空白字符(空格、制表符、换行符 等)处进行拆分
>>> 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 操作字符串的资料请关注编程网其它相关文章!
--结束END--
本文标题: python如何正确的操作字符串
本文链接: https://www.lsjlt.com/news/10980.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0