python字符串操作
时间: 2023-07-24 15:26:48 浏览: 40
Python中有很多字符串操作,以下是一些常见的:
1. 字符串拼接:使用加号(+)将两个字符串拼接起来,例如:
```
str1 = "hello"
str2 = "world"
result = str1 + str2
print(result) # 输出:helloworld
```
2. 字符串分割:使用split()方法将字符串按照指定的分隔符分割成一个列表,例如:
```
str = "hello,world"
result = str.split(",")
print(result) # 输出:['hello', 'world']
```
3. 字符串替换:使用replace()方法将字符串中指定的字符或字符串进行替换,例如:
```
str = "hello world"
result = str.replace("world", "python")
print(result) # 输出:hello python
```
4. 字符串大小写转换:使用upper()方法将字符串转换成大写,使用lower()方法将字符串转换成小写,例如:
```
str = "Hello World"
result1 = str.upper()
result2 = str.lower()
print(result1) # 输出:HELLO WORLD
print(result2) # 输出:hello world
```
5. 字符串格式化:使用format()方法将字符串中的占位符替换成指定的值,例如:
```
name = "Tom"
age = 20
result = "My name is {}, and I am {} years old.".format(name, age)
print(result) # 输出:My name is Tom, and I am 20 years old.
```
还有很多其他的字符串操作,你可以参考Python官方文档或者其他教程。