python怎么正确的操作字符串

发布时间:2021-06-21 10:08:31 作者:小新
来源:亿速云 阅读:190

这篇文章主要为大家展示了“python怎么正确的操作字符串”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“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)指定的。每个值都被插入字符串中,以替换用花括号括起的替换字段。 替换字段由如下部分组成,其中每个部分 都是可选的。

字段名

只需向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中几个很有用的常量

填充方法

字符串填充字符方法

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怎么正确的操作字符串”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!

推荐阅读:
  1. python 正确字符串处理(自己踩过的坑)
  2. python 字符串 查找 基本操作

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python 字符串

上一篇:如何用php关闭当前网页

下一篇:怎么使用Python实现感知器算法

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》