Python 字符串操作实例
时间: 2023-08-27 11:31:41 浏览: 103
Python提供了丰富的字符串操作方法,下面列举几个常用的字符串操作实例:
1. 字符串拼接
```
str1 = "Hello"
str2 = "World"
result = str1 + " " + str2
print(result) # Hello World
```
2. 字符串格式化
```
name = "Tom"
age = 20
result = "My name is {}, and I'm {} years old".format(name, age)
print(result) # My name is Tom, and I'm 20 years old
```
3. 字符串切片
```
str = "Hello World"
result = str[6:11]
print(result) # World
```
4. 字符串查找
```
str = "Hello World"
result = str.find("World")
print(result) # 6
```
5. 字符串替换
```
str = "Hello World"
result = str.replace("World", "Python")
print(result) # Hello Python
```
6. 字符串分割
```
str = "apple,banana,orange"
result = str.split(",")
print(result) # ['apple', 'banana', 'orange']
```
7. 字符串大小写转换
```
str = "Hello World"
result1 = str.upper()
result2 = str.lower()
print(result1) # HELLO WORLD
print(result2) # hello world
```
阅读全文