在本教程中,您将学习在 Python 中创建,格式化,修改和删除字符串。 此外,还将向您介绍各种字符串操作和函数。
Python 中的字符串是什么?
字符串是字符序列。
字符只是一个符号。 例如,英语具有 26 个字符。
计算机不处理字符,它们处理数字(二进制)。 即使您可能在屏幕上看到字符,它在内部也会作为 0 和 1 的组合进行存储和操作。
字符到数字的这种转换称为编码,而相反的过程是解码。 ASCII 和 Unicode 是一些常用的编码。
在 Python 中,字符串是 Unicode 字符序列。 引入 Unicode 是为了包括所有语言的每个字符并带来统一的编码。
如何在 Python 中创建字符串?
可以通过将字符括在单引号或双引号中来创建字符串。 Python 中甚至可以使用三引号,但通常用于表示多行字符串和文档字符串。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
# defining strings in Python # all of the following are equivalent my_string = 'Hello' print(my_string) my_string = "Hello" print(my_string) my_string = '''Hello''' print(my_string) # triple quotes string can extend multiple lines my_string = """Hello, welcome to the world of Python""" print(my_string) |
运行该程序时,输出为:
1 2 3 4 5 |
<samp>Hello Hello Hello Hello, welcome to the world of Python</samp> |
如何访问字符串中的字符?
我们可以使用索引访问单个字符,并使用切片访问一系列字符。 索引从 0 开始。尝试访问超出索引范围的字符将引发IndexError
。 索引必须是整数。 我们不能使用浮点数或其他类型,这将导致TypeError
。
Python 允许对其序列进行负索引。
-1
的索引指的是最后一项,-2
的索引指的是倒数第二项,依此类推。 我们可以使用切片运算符:
(冒号)访问字符串中的一系列项目。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
#Accessing string characters in Python str = 'programiz' print('str = ', str) #first character print('str[0] = ', str[0]) #last character print('str[-1] = ', str[-1]) #slicing 2nd to 5th character print('str[1:5] = ', str[1:5]) #slicing 6th to 2nd last character print('str[5:-2] = ', str[5:-2]) |
When we run the above program, we get the following output:
1 2 3 4 5 |
<samp>str = programiz str[0] = p str[-1] = z str[1:5] = rogr str[5:-2] = am</samp> |
如果尝试访问超出范围的索引或使用非整数的数字,则会出现错误。
1 2 3 4 5 6 7 8 9 |
# index must be in range >>> my_string[15] ... IndexError: string index out of range # index must be an integer >>> my_string[1.5] ... TypeError: string indices must be integers |
通过考虑索引位于元素之间,可以最好地可视化切片,如下所示。
如果要访问范围,则需要索引,该索引将从字符串中切出一部分。
如何更改或删除字符串?
字符串是不可变的。 这意味着字符串的元素一旦分配就无法更改。 我们可以简单地将不同的字符串重新分配给相同的名称。
1 2 3 4 5 6 7 |
>>> my_string = 'programiz' >>> my_string[5] = 'a' ... TypeError: 'str' object does not support item assignment >>> my_string = 'Python' >>> my_string 'Python' |
我们无法删除或删除字符串中的字符。 但是可以使用del
关键字完全删除字符串。
1 2 3 4 5 6 7 |
>>> del my_string[1] ... TypeError: 'str' object doesn't support item deletion >>> del my_string >>> my_string ... NameError: name 'my_string' is not defined |
Python 字符串操作
字符串可以执行许多操作,这使它成为 Python 中最常用的数据类型之一。
要了解有关 Python 中可用数据类型的更多信息,请访问: Python 数据类型
两个或多个字符串的连接
将两个或多个字符串连接为单个字符串称为连接。
+
运算符在 Python 中执行此操作。 只需将两个字符串字面值一起写就可以将它们连接在一起。
*
运算符可用于将字符串重复给定的次数。
1 2 3 4 5 6 7 8 9 |
# Python String Operations str1 = 'Hello' str2 ='World!' # using + print('str1 + str2 = ', str1 + str2) # using * print('str1 * 3 =', str1 * 3) |
When we run the above program, we get the following output:
1 2 |
<samp>str1 + str2 = HelloWorld! str1 * 3 = HelloHelloHello</samp> |
一起编写两个字符串字面值也将它们连接起来,就像+
运算符一样。
如果要在不同行中连接字符串,可以使用括号。
1 2 3 4 5 6 7 8 9 |
>>> # two string literals together >>> 'Hello ''World!' 'Hello World!' >>> # using parentheses >>> s = ('Hello ' ... 'World') >>> s 'Hello World' |
遍历字符串
我们可以使用循环遍历字符串。 这是一个计算字符串中l
数量的示例。
1 2 3 4 5 6 |
# Iterating through a string count = 0 for letter in 'Hello World': if(letter == 'l'): count += 1 print(count,'letters found') |
When we run the above program, we get the following output:
1 |
<samp>3 letters found</samp> |
字符串成员资格测试
我们可以使用关键字in
来测试字符串中是否存在子字符串。
1 2 3 4 |
>>> 'a' in 'program' True >>> 'at' not in 'battle' False |
可与字符串一起使用的内置函数
各种与序列一起使用的内置函数也可以与字符串一起使用。
一些常用的是enumerate()
和len()
。enumerate()
函数返回一个枚举对象。 它包含成对的字符串中所有项目的索引和值。 这对于迭代很有用。
同样,len()
返回字符串的长度(字符数)。
1 2 3 4 5 6 7 8 |
str = 'cold' # enumerate() list_enumerate = list(enumerate(str)) print('list(enumerate(str) = ', list_enumerate) #character count print('len(str) = ', len(str)) |
When we run the above program, we get the following output:
1 2 |
<samp>list(enumerate(str) = [(0, 'c'), (1, 'o'), (2, 'l'), (3, 'd')] len(str) = 4</samp> |
Python 字符串格式化
转义序列
如果我们要打印类似的字面值,He said, "What's there?"
,我们不能使用单引号或双引号。 由于文本本身包含单引号和双引号,因此将导致出现SyntaxError
。
1 2 3 4 5 6 |
>>> print("He said, "What's there?"") ... SyntaxError: invalid syntax >>> print('He said, "What's there?"') ... SyntaxError: invalid syntax |
解决此问题的一种方法是使用三引号。 另外,我们可以使用转义序列。
转义序列以反斜杠开头,并且以不同的方式解释。 如果我们使用单引号表示字符串,则必须对字符串内的所有单引号进行转义。 双引号也是如此。 这是代表上述文本的方法。
1 2 3 4 5 6 7 8 |
# using triple quotes print('''He said, "What's there?"''') # escaping single quotes print('He said, "What\'s there?"') # escaping double quotes print("He said, \"What's there?\"") |
When we run the above program, we get the following output:
1 2 3 |
<samp>He said, "What's there?" He said, "What's there?" He said, "What's there?"</samp> |
Here is a list of all the escape sequences supported by Python.
Escape Sequence | Description |
---|---|
\newline | 反斜杠 且 newline 忽略 |
\\ | 反斜杠 |
\’ | 单引号 |
\” | 双引号 |
\a | ASCII 铃声 |
\b | ASCII 退格 |
\f | ASCII 换页 |
\n | ASCII 换行 |
\r | ASCII 回车 |
\t | ASCII 水平制表 |
\v | ASCII 垂直制表 |
\ooo | 具有八进制值的字符 |
\xHH | 十六进制值为HH 的字符 |
Here are some examples
1 2 3 4 5 6 7 8 9 |
>>> print("C:\\Python32\\Lib") C:\Python32\Lib >>> print("This is printed\nin two lines") This is printed in two lines >>> print("This is \x48\x45\x58 representation") This is HEX representation |
原始字符串忽略转义序列
有时我们可能希望忽略字符串中的转义序列。 为此,我们可以将r
或R
放在字符串前面。 这意味着它是一个原始字符串,并且其中的任何转义序列都将被忽略。
1 2 3 4 5 |
>>> print("This is \x61 \ngood example") This is a good example >>> print(r"This is \x61 \ngood example") This is \x61 \ngood example |
格式化字符串的format()
方法
字符串对象可用的format()
方法在格式化字符串方面非常通用且功能强大。 格式字符串包含大括号{}
作为占位符或将被替换的替换字段。
我们可以使用位置参数或关键字参数来指定顺序。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
# Python string format() method # default(implicit) order default_order = "{}, {} and {}".format('John','Bill','Sean') print('\n--- Default Order ---') print(default_order) # order using positional argument positional_order = "{1}, {0} and {2}".format('John','Bill','Sean') print('\n--- Positional Order ---') print(positional_order) # order using keyword argument keyword_order = "{s}, {b} and {j}".format(j='John',b='Bill',s='Sean') print('\n--- Keyword Order ---') print(keyword_order) |
When we run the above program, we get the following output:
1 2 3 4 5 6 7 8 |
<samp>--- Default Order --- John, Bill and Sean --- Positional Order --- Bill, John and Sean --- Keyword Order --- Sean, Bill and John</samp> |
format()
方法可以具有可选的格式规范。 它们使用冒号与字段名称分隔。 例如,我们可以在给定的空间中将字符串<
左对齐,>
右对齐或将^
居中对齐。
我们还可以将整数格式化为二进制,十六进制等,并且浮点数可以四舍五入或以指数格式显示。 您可以使用大量的格式。 请访问此处,以获取[format()](/python-programming/methods/string/format)
方法可用的所有字符串格式。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
>>> # formatting integers >>> "Binary representation of {0} is {0:b}".format(12) 'Binary representation of 12 is 1100' >>> # formatting floats >>> "Exponent representation: {0:e}".format(1566.345) 'Exponent representation: 1.566345e+03' >>> # round off >>> "One third is: {0:.3f}".format(1/3) 'One third is: 0.333' >>> # string alignment >>> "|{:<10}|{:^10}|{:>10}|".format('butter','bread','ham') '|butter | bread | ham|' |
旧式格式化
我们甚至可以格式化字符串,例如 C 编程语言中使用的旧sprintf()
样式。 我们使用%
运算符来完成此操作。
1 2 3 4 5 |
>>> x = 12.3456789 >>> print('The value of x is %3.2f' %x) The value of x is 12.35 >>> print('The value of x is %3.4f' %x) The value of x is 12.3457 |
常见的 Python 字符串方法
字符串对象有许多可用的方法。 我们上面提到的format()
方法就是其中之一。 某些常用的方法是lower()
,upper()
,join()
,split()
,find()
和replace()
等。
1 2 3 4 5 6 7 8 9 10 11 12 |
>>> "PrOgRaMiZ".lower() 'programiz' >>> "PrOgRaMiZ".upper() 'PROGRAMIZ' >>> "This will split all words into a list".split() ['This', 'will', 'split', 'all', 'words', 'into', 'a', 'list'] >>> ' '.join(['This', 'will', 'join', 'all', 'words', 'into', 'a', 'string']) 'This will join all words into a string' >>> 'Happy New Year'.find('ew') 7 >>> 'Happy New Year'.replace('Happy','Brilliant') 'Brilliant New Year' |