在Python中,字符串是一种不可变的序列数据类型,用于表示文本信息。字符串在Python编程中应用广泛,掌握字符串的操作对于数据处理、文本分析和Web开发等至关重要。
字符串类型概览
Python中的字符串具有以下特点:
- 不可变性:字符串一旦创建,其内容不能更改
- 序列类型:字符串是由字符组成的序列,支持索引和切片操作
- Unicode支持:Python字符串支持Unicode字符,可以表示各种语言的文本
- 多种引号:可以使用单引号、双引号或三引号创建字符串
字符串的创建
Python提供了多种方式创建字符串:
| 创建方式 |
示例 |
说明 |
| 单引号 |
'Hello, World!' |
简单的字符串创建 |
| 双引号 |
"Hello, World!" |
允许在字符串中包含单引号 |
| 三引号 |
'''多行字符串''' 或 """多行字符串""" |
创建多行字符串,保留格式 |
| str()函数 |
str(123) |
将其他类型转换为字符串 |
str1 = 'Hello, World!'
str2 = "Python字符串"
str3 = '''这是一个
多行
字符串'''
str4 = str(123)
print(str1)
print(str2)
print(str3)
print(str4)
quote1 = "He said, 'Hello!'"
quote2 = 'She said, "Hi!"'
quote3 = "He said, \"Hello!\""
print(quote1)
print(quote2)
print(quote3)
字符串基本操作
字符串支持多种基本操作,包括索引、切片、连接和重复等。
| 操作 |
运算符/方法 |
示例 |
结果 |
| 索引 |
[index] |
"Python"[0] |
'P' |
| 切片 |
[start:end:step] |
"Python"[0:3] |
'Pyt' |
| 连接 |
+ |
"Hello" + "World" |
'HelloWorld' |
| 重复 |
* |
"Hi" * 3 |
'HiHiHi' |
| 成员检测 |
in |
'P' in "Python" |
True |
| 长度 |
len() |
len("Python") |
6 |
s = "Python Programming"
print("第一个字符:", s[0])
print("最后一个字符:", s[-1])
print("前6个字符:", s[0:6])
print("从第7个开始:", s[7:])
print("每隔一个字符:", s[::2])
s1 = "Hello"
s2 = "World"
print(s1 + " " + s2)
print(s1 * 3)
print("'Pro' in s:", 'Pro' in s)
print("字符串长度:", len(s))
字符串格式化
Python提供了多种字符串格式化方法,用于将变量插入到字符串中。
| 格式化方法 |
示例 |
说明 |
| % 格式化 |
"Hello, %s!" % name |
传统格式化方法 |
| str.format() |
"Hello, {}!".format(name) |
Python 2.6+ 引入 |
| f-string |
f"Hello, {name}!" |
Python 3.6+ 引入,推荐使用 |
name = "Alice"
age = 25
height = 1.65
message1 = "姓名: %s, 年龄: %d, 身高: %.2f米" % (name, age, height)
print(message1)
message2 = "姓名: {}, 年龄: {}, 身高: {:.2f}米".format(name, age, height)
print(message2)
message3 = f"姓名: {name}, 年龄: {age}, 身高: {height:.2f}米"
print(message3)
a = 5
b = 3
result = f"{a} + {b} = {a + b}"
print(result)
字符串常用方法
Python字符串提供了丰富的方法,用于处理和操作字符串。
| 方法 |
描述 |
示例 |
结果 |
| upper() |
转换为大写 |
"hello".upper() |
'HELLO' |
| lower() |
转换为小写 |
"HELLO".lower() |
'hello' |
| strip() |
去除两端空白 |
" hello ".strip() |
'hello' |
| split() |
分割字符串 |
"a,b,c".split(",") |
['a', 'b', 'c'] |
| join() |
连接字符串 |
",".join(['a','b','c']) |
'a,b,c' |
| replace() |
替换子字符串 |
"hello".replace("l","x") |
'hexxo' |
| find() |
查找子字符串 |
"hello".find("l") |
2 |
| startswith() |
检查前缀 |
"hello".startswith("he") |
True |
| endswith() |
检查后缀 |
"hello".endswith("lo") |
True |
s = " Python Programming "
print("大写:", s.upper())
print("小写:", s.lower())
print("去除两端空白:", s.strip())
words = "apple,banana,orange"
fruit_list = words.split(",")
print("分割结果:", fruit_list)
new_words = "-".join(fruit_list)
print("连接结果:", new_words)
text = "I like cats. Cats are cute."
new_text = text.replace("cats", "dogs")
print("替换后:", new_text)
sentence = "Python is a powerful programming language"
print("'powerful'的位置:", sentence.find("powerful"))
print("以'Python'开头:", sentence.startswith("Python"))
print("以'language'结尾:", sentence.endswith("language"))
转义字符
转义字符用于表示一些特殊字符或无法直接输入的字符。
| 转义字符 |
描述 |
示例 |
结果 |
| \n |
换行 |
"Hello\nWorld" |
Hello World |
| \t |
制表符 |
"Hello\tWorld" |
Hello World |
| \\ |
反斜杠 |
"C:\\Users" |
C:\Users |
| \" |
双引号 |
"He said, \"Hello\"" |
He said, "Hello" |
| \' |
单引号 |
'It\'s mine' |
It's mine |
| \u |
Unicode字符 |
"\u4f60\u597d" |
你好 |
multiline = "第一行\n第二行\n\t缩进的第三行"
print(multiline)
path = "C:\\Users\\Documents\\file.txt"
print("文件路径:", path)
raw_path = r"C:\Users\Documents\file.txt"
print("原始字符串路径:", raw_path)
chinese = "\u4f60\u597d\uff0c\u4e16\u754c\uff01"
print("Unicode字符串:", chinese)
字符串编码
Python 3中的字符串默认使用Unicode编码,可以表示世界上大多数语言的字符。
s1 = "Hello, 世界! 🌍"
print(s1)
s = "Python编程"
encoded = s.encode('utf-8')
print("UTF-8编码:", encoded)
decoded = encoded.decode('utf-8')
print("解码后:", decoded)
注意: Python 2和Python 3在字符串处理上有很大不同。Python 3中的字符串默认是Unicode,而Python 2中需要显式使用u"字符串"前缀。建议使用Python 3进行字符串处理。
提示: 对于大量字符串连接操作,使用join()方法比使用+操作符更高效,因为字符串是不可变对象,每次使用+连接都会创建新的字符串对象。