Python 程序设计 - 11. 字符串
1. 引言
在 Python 中,字符串(str)是一种非常常用的数据类型,它是由一系列字符组成的不可变序列。字符串可以包含字母、数字、符号以及空格,并且它支持多种操作,如切片、拼接、查找、替换等。掌握字符串的基本操作是 Python 编程的基础之一,几乎所有的应用程序都需要处理字符串。
2. 字符串基本概念
Python 中的字符串是通过一对单引号(')或双引号(")来表示的。Python 也支持多行字符串,可以用三重引号(''' 或 """)来表示。
定义字符串的方式:
string1 = "Hello, World!"
string2 = 'Python Programming'
string3 = '''This is a
multi-line string.'''
string1和string2都是普通的单行字符串。string3是一个多行字符串,换行符会被保留。
3. 字符串的常用操作
3.1 字符串拼接
可以通过 + 运算符将多个字符串连接在一起:
greeting = "Hello"
name = "Alice"
message = greeting + ", " + name + "!"
print(message) # 输出: Hello, Alice!
3.2 字符串重复
可以使用 * 运算符将字符串重复多次:
word = "Python "
repeated_word = word * 3
print(repeated_word) # 输出: Python Python Python
3.3 字符串长度
使用 len() 函数可以获取字符串的长度(即字符的个数):
text = "Hello"
print(len(text)) # 输出: 5
3.4 字符串切片
切片操作可以获取字符串的一部分。切片语法如下:
string[start:end:step]
start:切片的起始索引(包含)。end:切片的结束索引(不包含)。step:步长(默认是 1)。
text = "Python Programming"
print(text[0:6]) # 输出: Python
print(text[7:]) # 输出: Programming
print(text[:6]) # 输出: Python
print(text[::2]) # 输出: Pto rgamn
3.5 字符串查找
find():返回子字符串第一次出现的位置,如果找不到,返回-1。
text = "Hello, Python!"
position = text.find("Python")
print(position) # 输出: 7
in:检查一个子字符串是否存在于另一个字符串中,返回布尔值。
text = "Hello, Python!"
print("Python" in text) # 输出: True
print("Java" in text) # 输出: False
3.6 字符串替换
replace() 方法可以将字符串中的某个子字符串替换为另一个子字符串:
text = "Hello, Python!"
new_text = text.replace("Python", "World")
print(new_text) # 输出: Hello, World!
3.7 字符串分割
split() 方法将字符串按照指定的分隔符拆分成多个子字符串,返回一个列表:
text = "Python is awesome"
words = text.split(" ")
print(words) # 输出: ['Python', 'is', 'awesome']
3.8 字符串大小写转换
lower():将字符串转换为小写。upper():将字符串转换为大写。capitalize():将字符串的第一个字符转换为大写,其他字符为小写。
text = "hello, Python!"
print(text.lower()) # 输出: hello, python!
print(text.upper()) # 输出: HELLO, PYTHON!
print(text.capitalize()) # 输出: Hello, python!
4. 字符串格式化
4.1 使用 % 进行格式化
% 是一种较老的格式化方式,可以在字符串中插入变量。
name = "Alice"
age = 25
message = "My name is %s, and I am %d years old." % (name, age)
print(message) # 输出: My name is Alice, and I am 25 years old.
4.2 使用 str.format() 进行格式化
str.format() 是 Python 3 中推荐的格式化方式,它支持更灵活的格式化方法。
name = "Alice"
age = 25
message = "My name is {}, and I am {} years old.".format(name, age)
print(message) # 输出: My name is Alice, and I am 25 years old.
4.3 使用 f-string 进行格式化
Python 3.6 及以上版本可以使用 f-string,这是目前最简洁、最快速的格式化方式。
name = "Alice"
age = 25
message = f"My name is {name}, and I am {age} years old."
print(message) # 输出: My name is Alice, and I am 25 years old.
5. 常见字符串方法总结
| 方法 | 描述 |
|---|---|
len(string) | 返回字符串的长度 |
string.lower() | 将字符串转换为小写 |
string.upper() | 将字符串转换为大写 |
string.capitalize() | 将字符串的第一个字符转换为大写,其他字符为小写 |
string.find(sub) | 查找子字符串 sub,返回首次出现的位置,未找到返回 -1 |
string.replace(old, new) | 将字符串中的 old 替换为 new |
string.split() | 按照空格或指定字符分割字符串,返回一个列表 |
string.strip() | 去除字符串首尾的空白字符 |
string.isdigit() | 判断字符串是否只包含数字字符,返回 True 或 False |
string.join(iterable) | 将 iterable 中的元素用当前字符串连接起来并返回新字符串 |
6. 练习题
练习 1:字符串拼接
first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name
print(full_name) # 输出: John Doe
练习 2:判断一个字符串是否包含某个子字符串
text = "Welcome to Python programming!"
if "Python" in text:
print("找到了 Python")
else:
print("没有找到 Python")
练习 3:将一个字符串转换为大写
text = "hello, world!"
print(text.upper()) # 输出: HELLO, WORLD!
练习 4:替换字符串中的某个字符
text = "I like apples"
new_text = text.replace("apples", "oranges")
print(new_text) # 输出: I like oranges
练习 5:分割字符串并输出每个单词
sentence = "I love programming"
words = sentence.split()
for word in words:
print(word)
7. 总结
字符串是 Python 中常用且强大的数据类型,掌握字符串的基本操作可以使得数据处理和文本处理更加高效。通过本章节的学习,你已经了解了字符串的定义、常用操作、格式化方法以及如何使用字符串进行实际编程任务。继续练习,将帮助你更加熟悉字符串的各种使用场景。
评论区