Python 字符串

在 Python 中,字符串是字符序列。例如,"hello" 是一个包含字符序列 'h''e''l''l''o' 的字符串。

我们使用单引号或双引号来表示 Python 中的字符串。例如:

# create a string using double quotes
string1 = "Python programming"

# create a string using single quotes
string1 = 'Python programming'

这里,我们创建了一个名为 string1 的字符串变量。该变量用字符串 "Python Programming" 初始化。


示例:Python 字符串

# create string type variables

name = "Python"
print(name)

message = "I love Python."
print(message)

输出

Python
I love Python.

在上面的例子中,我们创建了字符串类型的变量:namemessage,其值分别为 "Python""I love Python"

这里,我们使用双引号来表示字符串,但我们也可以使用单引号。


在 Python 中访问字符串字符

我们可以通过三种方式访问字符串中的字符。

  • 索引 一种方法是将字符串视为列表并使用索引值。例如:
greet = 'hello'

# access 1st index element
print(greet[1]) # "e"
  • 负索引:与列表类似,Python 允许其字符串使用负索引。例如:
greet = 'hello'

# access 4th last element
print(greet[-4]) # "e"
  • 切片 使用切片运算符冒号 : 访问字符串中的一系列字符。例如:
greet = 'Hello'

# access character from 1st index to 3rd index
print(greet[1:4])  # "ell"

注意:如果我们尝试访问超出范围的索引或使用非整数数字,我们将收到错误。


Python 字符串是不可变的

在 Python 中,字符串是不可变的。这意味着字符串的字符不能更改。例如:

message = 'Hola Amigos'
message[0] = 'H'
print(message)

输出

TypeError: 'str' object does not support item assignment

但是,我们可以将变量名分配给一个新的字符串。例如:

message = 'Hola Amigos'

# assign new string to message variable
message = 'Hello Friends'

print(message); # prints "Hello Friends"

Python 多行字符串

我们还可以在 Python 中创建多行字符串。为此,我们使用三重双引号 """ 或三重单引号 '''。例如:

# multiline string 
message = """
Never gonna give you up
Never gonna let you down
"""

print(message)

输出

Never gonna give you up
Never gonna let you down

在上面的示例中,封闭的三重引号内的任何内容都是一个多行字符串。


Python 字符串操作

字符串可以执行许多操作,这使其成为 Python 中最常用的数据类型之一。

1. 比较两个字符串

我们使用 == 运算符来比较两个字符串。如果两个字符串相等,运算符返回 True。否则,返回 False。例如:

str1 = "Hello, world!"
str2 = "I love Swift."
str3 = "Hello, world!"

# compare str1 and str2
print(str1 == str2)

# compare str1 and str3
print(str1 == str3)

输出

False
True

在上面的例子中:

  1. str1str2 不相等。因此,结果为 False
  2. str1str3 相等。因此,结果为 True

2. 连接两个或多个字符串

在 Python 中,我们可以使用 + 运算符连接(拼接)两个或多个字符串。

greet = "Hello, "
name = "Jack"

# using + operator
result = greet + name
print(result)

# Output: Hello, Jack

在上面的示例中,我们使用 + 运算符连接了两个字符串:greetname


遍历 Python 字符串

我们可以使用 for 循环遍历字符串。例如:

greet = 'Hello'

# iterating through greet string
for letter in greet:
    print(letter)

输出

H
e
l
l
o

Python 字符串长度

在 Python 中,我们使用 len() 方法查找字符串的长度。例如:

greet = 'Hello'

# count length of greet string
print(len(greet))

# Output: 5

字符串成员测试

我们可以使用关键字 in 测试子字符串是否存在于字符串中。

print('a' in 'program') # True
print('at' not in 'battle') # False

Python 字符串的方法

除了上面提到的那些,Python 中还有各种字符串方法。以下是一些方法:

方法 描述
upper() 将字符串转换为大写
lower() 将字符串转换为小写
partition() 返回一个元组
replace() 替换内部子字符串
find() 返回子字符串第一次出现的索引
rstrip() 删除尾部字符
split() 从左侧拆分字符串
startswith() 检查字符串是否以指定字符串开头
isnumeric() 检查数字字符
index() 返回子字符串的索引

Python 中的转义序列

转义序列用于转义字符串中存在的某些字符。

假设我们需要在字符串中同时包含双引号和单引号,

example = "He said, "What's there?""

print(example) # throws error

由于字符串用单引号或双引号表示,编译器会将 "He said, " 视为一个字符串。因此,上面的代码将导致错误。

为了解决这个问题,我们在 Python 中使用转义字符 \

# escape double quotes
example = "He said, \"What's there?\""

# escape single quotes
example = 'He said, "What\'s there?"'

print(example)

# Output: He said, "What's there?"

这是 Python 支持的所有转义序列的列表。

转义序列 描述
\\ 反斜杠
\' 单引号
\" 双引号
\a ASCII 响铃
\b ASCII 退格
\f ASCII 换页
\n ASCII 换行
\r ASCII 回车
\t ASCII 水平制表符
\v ASCII 垂直制表符
\ooo 八进制值为 ooo 的字符
\xHH 十六进制值为 HH 的字符

Python 字符串格式化 (f-字符串)

Python f-字符串使得打印值和变量变得容易。例如:

name = 'Cathy'
country = 'UK'

print(f'{name} is from {country}')

输出

Cathy is from UK

这里,f'{name} is from {country}' 是一个 f-字符串

这种新的格式化语法功能强大且易于使用。从现在开始,我们将使用 f-字符串来打印字符串和变量。


另请阅读

在我们结束之前,让我们测试一下你对 Python 字符串的知识!你能解决以下挑战吗?

挑战

编写一个函数,将字符串中的每个字母加倍。

  • 对于输入 'hello',返回值应为 'hheelllloo'

视频:Python 字符串

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战