python中的字符串
1. 创建字符串
字符串可以通过多种方式创建:
- 单引号和双引号:可以使用单引号或双引号来定义字符串。
str1 = 'Hello, World!'
str2 = "Hello, World!"
- 三重引号:用于创建多行字符串,支持换行。
str3 = """This is a
multi-line string."""
2. 字符串的基本操作
2.1 连接字符串
使用 +
运算符连接多个字符串。
greeting = "Hello"
name = "Alice"
message = greeting + ", " + name + "!" # "Hello, Alice!"
2.2 重复字符串
使用 *
运算符重复字符串。
repeat = "Ha" * 3 # "HaHaHa"
2.3 字符串长度
使用 len()
函数获取字符串的长度。
length = len(message) # 13
3. 字符串索引和切片
3.1 字符串索引
字符串是可索引的,可以通过索引访问单个字符,索引从0开始。
first_char = message[0] # 'H'
last_char = message[-1] # '!'
3.2 字符串切片
切片可以获取字符串的子串,语法为 str[start:end]
。
substring = message[0:5] # 'Hello'
substring2 = message[7:] # 'Alice!'
substring3 = message[:5] # 'Hello'
4. 字符串方法
Python提供了许多内置字符串方法,以下是一些常用的方法:
str.lower()
:将字符串转换为小写。
text = "Hello, World!"
print(text.lower()) # 'hello, world!'
str.upper()
:将字符串转换为大写。
print(text.upper()) # 'HELLO, WORLD!'
str.strip()
:去除字符串两端的空白字符。
text_with_spaces = " Hello, World! "
print(text_with_spaces.strip()) # 'Hello, World!'
str.split()
:将字符串分割为列表。
csv = "apple,banana,cherry"
fruits = csv.split(",") # ['apple', 'banana', 'cherry']
str.replace(old, new)
:替换字符串中的子串。
new_text = text.replace("World", "Python") # 'Hello, Python!'
str.find(sub)
:查找子串的位置,未找到返回-1。
index = text.find("World") # 7
5. 字符串格式化
Python支持多种字符串格式化方法:
5.1 f-字符串(Python 3.6+)
使用 f
前缀,可以直接在字符串中嵌入变量。
name = "Alice"
age = 30
formatted = f"{name} is {age} years old." # 'Alice is 30 years old.'
5.2 str.format()
方法
使用 {}
占位符和 format()
方法进行格式化。
formatted = "{} is {} years old.".format(name, age) # 'Alice is 30 years old.'
5.3 百分号格式化
使用 %
运算符进行格式化。
formatted = "%s is %d years old." % (name, age) # 'Alice is 30 years old.'
6. 转义字符
在字符串中使用反斜杠 \
来转义特殊字符,例如:
\'
:单引号\"
:双引号\\
:反斜杠\n
:换行\t
:制表符
quote = "He said, \"Hello!\""
newline = "First line.\nSecond line."
7. 原始字符串
使用 r
前缀创建原始字符串,忽略转义字符,适合正则表达式等场景。
raw_string = r"C:\Users\Name\Documents" # 不会转义
8. 字符串不可变性
字符串在Python中是不可变的,这意味着一旦创建,字符串的内容就不能被更改。任何对字符串的操作都会返回一个新的字符串。
original = "Hello"
modified = original.replace("H", "J") # 'Jello'
print(original) # 'Hello',原始字符串未改变
9. 字符串的迭代
可以使用 for
循环遍历字符串中的每个字符。
for char in "Hello":
print(char) # 输出每个字符
10. 字符串的比较
字符串可以使用比较运算符进行比较,比较是基于字典序的。
print("apple" < "banana") # True
print("apple" == "apple") # True