Python中常见的对字符串操作有哪些,具体怎么做
Admin 2022-07-05 群英技术资讯 730 次浏览
这篇文章主要介绍“Python中常见的对字符串操作有哪些,具体怎么做”,有一些人在Python中常见的对字符串操作有哪些,具体怎么做的问题上存在疑惑,接下来小编就给大家来介绍一下相关的内容,希望对大家解答有帮助,有这个方面学习需要的朋友就继续往下看吧。字符串是 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']
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:mmqy2019@163.com进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。
猜你喜欢
内容介绍写在前面创建一个文档先实现第一步,写入一个标题添加文字段落列表的添加图片的添加表格添加相关样式设置页眉和页脚写在前面python-docx不支持doc文档,一定要注意该点,如果使用do
这篇文章给大家分享的是Django模板中两个变量运算的实现,文中示例代码介绍的非常详细,对大家学习和理解Django模板中的变量运算有一定的帮助,感兴趣的朋友接下来一起跟随小编看看吧。
Python有广泛丰富的第三方库,在没有特殊定制下,避免了重复造轮子。本文将利用radar库实现生成随机的日期或时间,文中的示例代码讲解详细,感兴趣的可以了解一下
内容介绍基础代码改进再次改进:又次改进:改进:----加准确率基础代码pred_y=test_output.data.numpy()pred_y=pred_y.flatten()print(p
这篇文章主要介绍了prod()与cumprod()区别cumsum(),具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
成为群英会员,开启智能安全云计算之旅
立即注册Copyright © QY Network Company Ltd. All Rights Reserved. 2003-2020 群英 版权所有
增值电信经营许可证 : B1.B2-20140078 粤ICP备09006778号 域名注册商资质 粤 D3.1-20240008