华域联盟 Python 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)指定的。每个值都被插入字符串中,以替换用花括号括起的替换字段。 替换字段由如下部分组成,其中每个部分 都是可选的。

  • 字段名:索引或标识符,指出要设置哪个值的格式并使用结果来替换该字段。除指定值 外,还可指定值的特定部分,如列表的元素。
  • 转换标志:跟在叹号后面的单个字符。当前支持的字符包括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 操作字符串的资料请关注华域联盟其它相关文章!

您可能感兴趣的文章:

本文由 华域联盟 原创撰写:华域联盟 » python如何正确的操作字符串

转载请保留出处和原文链接:https://www.cnhackhy.com/28930.htm

本文来自网络,不代表华域联盟立场,转载请注明出处。

作者: sterben

发表回复

联系我们

联系我们

2551209778

在线咨询: QQ交谈

邮箱: [email protected]

工作时间:周一至周五,9:00-17:30,节假日休息

关注微信
微信扫一扫关注我们

微信扫一扫关注我们

关注微博
返回顶部