Python 字符串

字符串是Python中最常用的数据类型,就像字母和单词组成的一句句子一样。在Python中,字符串是由字符组成的序列,用单引号(')或双引号(")包围。

字符串是什么?

字符串就是文本数据!在Python中,我们可以创建包含字母、数字、空格和符号的字符串。

例如:"Hello World"、'Python很有趣'、"12345" 都是有效的字符串。

创建字符串

创建字符串非常简单,只需要用引号把文本内容包围起来:

# 使用单引号创建字符串
my_string = '这是一个字符串'
print(my_string)

# 使用双引号创建字符串
another_string = "这也是一个字符串"
print(another_string)

# 使用三重引号创建多行字符串
multi_line = """这是第一行
这是第二行
这是第三行"""

print(multi_line)
小贴士

单引号和双引号在Python中是等效的,但使用三重引号('''或""")可以创建包含换行符的多行字符串。

字符串操作

Python提供了多种操作字符串的方式:

1. 连接字符串

使用加号(+)连接两个字符串:

first_name = "小明"
last_name = "张"
full_name = first_name + " " + last_name
print(full_name) # 输出: 小明 张

2. 重复字符串

使用星号(*)重复字符串:

laugh = "哈"
big_laugh = laugh * 5
print(big_laugh) # 输出: 哈哈哈哈哈哈

3. 获取字符串长度

使用len()函数获取字符串长度:

s = "我爱Python编程"
length = len(s)
print("字符串长度:", length) # 输出: 9

访问字符串中的字符

在Python中,我们可以通过索引访问字符串中的单个字符:

s = "Python"
print(s[0]) # 输出: P (索引从0开始)
print(s[3]) # 输出: h
print(s[-1]) # 输出: n (负数索引表示从后往前)
重要提示

Python中的字符串是不可变的,这意味着一旦创建了一个字符串,就不能改变它的内容。

例如:s[0] = 'J' 会引发错误!

字符串切片

切片允许我们获取字符串的一部分:

语法 说明 示例
s[start:end] 获取从start到end-1的子串 s[2:5]
s[:end] 从开头到end-1的子串 s[:3]
s[start:] 从start到结尾的子串 s[4:]
s[:] 整个字符串 s[:]
s[start:end:step] 带步长的切片 s[0:10:2]
切片示例
s = "Python编程很有趣"

print(s[0:6]) # 输出: Python
print(s[7:]) # 输出: 很有趣
print(s[:6]) # 输出: Python
print(s[::2]) # 输出: Pto编很趣 (隔一个取一个)
print(s[-3:]) # 输出: 很有趣

常用字符串方法

Python提供了许多内置方法来操作字符串:

方法 说明 示例
upper() 将字符串转为大写 "hello".upper() → "HELLO"
lower() 将字符串转为小写 "HELLO".lower() → "hello"
strip() 移除字符串两端空白 " hello ".strip() → "hello"
replace() 替换字符串中的内容 "hello".replace("l", "w") → "hewwo"
split() 分割字符串为列表 "apple,banana,orange".split(",") → ["apple", "banana", "orange"]
find() 查找子串位置 "hello".find("e") → 1
count() 计算子串出现次数 "banana".count("na") → 2
startswith() 检查是否以指定字符串开头 "hello".startswith("he") → True
endswith() 检查是否以指定字符串结尾 "world".endswith("ld") → True
方法使用示例
text = " Python编程很有趣! "

# 移除空格并转为大写
clean_text = text.strip().upper()
print(clean_text) # 输出: PYTHON编程很有趣!

# 替换"有趣"为"有用"
new_text = text.replace("有趣", "有用")
print(new_text) # 输出: Python编程很有用!

# 查找"编程"的位置
position = text.find("编程")
print("位置:", position) # 输出: 8

字符串格式化

Python提供了多种格式化字符串的方法:

1. 使用%操作符(旧方法)

name = "小明"
age = 10
s = "姓名: %s, 年龄: %d岁" % (name, age)
print(s) # 输出: 姓名: 小明, 年龄: 10岁

2. 使用format()方法

name = "小红"
score = 95.5
s = "姓名: {}, 分数: {:.1f}".format(name, score)
print(s) # 输出: 姓名: 小红, 分数: 95.5

3. 使用f-strings(Python 3.6+推荐)

fruit = "苹果"
price = 5.99
quantity = 3
s = f"水果: {fruit}, 单价: {price}元, 总价: {price * quantity:.2f}元"
print(s) # 输出: 水果: 苹果, 单价: 5.99元, 总价: 17.97元
格式化小技巧

f-strings是最新、最简洁的字符串格式化方法,可以让你在字符串中直接嵌入变量和表达式!

字符串检查方法

Python提供了一些方法来检查字符串的内容:

方法 说明 示例
isalpha() 是否只包含字母 "Hello".isalpha() → True
isdigit() 是否只包含数字 "1234".isdigit() → True
isalnum() 是否只包含字母和数字 "abc123".isalnum() → True
isspace() 是否只包含空白字符 " \t".isspace() → True
isupper() 是否所有字母都是大写 "HELLO".isupper() → True
islower() 是否所有字母都是小写 "hello".islower() → True
检查方法示例
# 检查用户输入
user_input = input("请输入用户名: ")

if user_input.isdigit():
    print("用户名不能只包含数字!")
elif user_input.isspace() or user_input == "":
    print("用户名不能为空!")
else:
    print("用户名有效!")
重要注意事项

在Python中,字符串是不可变的!这意味着你不能直接修改字符串中的字符:

s = "hello"
# 以下操作会引发错误!
# s[0] = 'H'

# 正确做法是创建新字符串
new_s = "H" + s