字符串是Python中最受欢迎、最常使用的数据类型。可以通过用引号括起字符来创建它们。 Python将单引号与双引号相同。创建字符串和向一个变量赋值一样简单。 例如 –
var1 = 'Hello World!'
var2 = "Python Programming"
Python
1.访问字符串中的值
Python不支持字符类型; 字符会被视为长度为1的字符串,因此也被认为是一个子字符串。要访问子串,请使用方括号的切片加上索引或直接使用索引来获取子字符串。 例如 –
#!/usr/bin/python3
var1 = 'Hello World!'
var2 = "Python Programming"
print ("var1[0]: ", var1[0])
print ("var2[1:5]: ", var2[1:5]) # 切片加索引
Python
当执行上述代码时,会产生以下结果 –
var1[0]: H
var2[1:5]: ytho
Shell
2.更新字符串
可以通过将变量分配给另一个字符串来“更新”现有的字符串。 新值可以与其原值相关或完全不同的字符串。 例如 –
#!/usr/bin/python3
var1 = 'Hello World!'
print ("Updated String :- ", var1[:6] + 'Python')
Python
当执行上述代码时,会产生以下结果 –
Updated String :- Hello Python
Shell
3.转义字符
下表是可以用反斜杠表示法表示转义或不可打印字符的列表。单引号以及双引号字符串的转义字符被解析。
4.字符串特殊运算符
假设字符串变量a保存字符串值’Hello‘,变量b保存字符串值’Python‘,那么 –
5.字符串格式化运算符
Python最酷的功能之一是字符串格式运算符%。 这个操作符对于字符串是独一无二的,弥补了C语言中 printf()系列函数。 以下是一个简单的例子 –
#!/usr/bin/python3
print ("My name is %s and weight is %d kg!" % ('Maxsu', 71))
Python
当执行上述代码时,会产生以下结果 –
My name is Maxsu and weight is 71 kg!
Shell
以下是可以与%符号一起使用的完整符号集列表 –
其他支持的符号和功能如下表所列 –
6.三重引号
Python中的三重引号允许字符串跨越多行,包括逐字记录的新一行,TAB和任何其他特殊字符。
三重引号的语法由三个连续的单引号或双引号组成。
#!/usr/bin/python3
para_str = """this is a long string that is made up of
several lines and non-printable characters such as
TAB ( t ) and they will show up that way when displayed.
NEWLINEs within the string, whether explicitly given like
this within the brackets [ n ], or just a NEWLINE within
the variable assignment will also show up.
"""
print (para_str)
Shell
当执行上述代码时,会产生以下结果。注意每个单独的特殊字符如何被转换成其打印形式,它是直到最后一个NEWLINEs在“up”之间的字符串的末尾,并关闭三重引号。 另请注意,NEWLINEs可能会在一行或其转义码(n)的末尾显式显示回车符 –
this is a long string that is made up of
several lines and non-printable characters such as
TAB ( ) and they will show up that way when displayed.
NEWLINEs within the string, whether explicitly given like
this within the brackets [
], or just a NEWLINE within
the variable assignment will also show up.
Shell
原始字符串根本不将反斜杠视为特殊字符。放入原始字符串的每个字符都保持所写的方式 –
#!/usr/bin/python3
print ('C:\nowhere')
Python
当执行上述代码时,会产生以下结果 –
C:nowhere
Shell
现在演示如何使用原始的字符串。将表达式修改为如下 –
#!/usr/bin/python3
print (r'C:\nowhere')
Shell
当执行上述代码时,会产生以下结果 –
C:\nowhere
Shell
7.Unicode字符串
在Python 3中,所有的字符串都用Unicode表示。在Python 2内部存储为8位ASCII,因此需要附加’u‘使其成为Unicode,而现在不再需要了。
内置字符串方法
Python包括以下内置方法来操作字符串 –