python字符串操作
时间: 2023-09-21 14:03:25 浏览: 44
Python的字符串是一种不可变的序列类型,可以使用许多内置函数和方法来操作它们。下面是一些常见的字符串操作:
1. 字符串连接:
```python
str1 = "hello"
str2 = "world"
print(str1 + str2) # 输出:helloworld
```
2. 字符串格式化:
```python
name = "Tom"
age = 20
print("My name is %s, I'm %d years old." % (name, age)) # 输出:My name is Tom, I'm 20 years old.
```
3. 字符串切片:
```python
str = "hello world"
print(str[1:5]) # 输出:ello
```
4. 字符串查找:
```python
str = "hello world"
print(str.find("world")) # 输出:6
```
5. 字符串替换:
```python
str = "hello world"
print(str.replace("world", "python")) # 输出:hello python
```
6. 字符串大小写转换:
```python
str = "Hello World"
print(str.lower()) # 输出:hello world
print(str.upper()) # 输出:HELLO WORLD
```
7. 字符串分割:
```python
str = "hello,world"
print(str.split(",")) # 输出:['hello', 'world']
```
除了上面列出的操作外,Python还有许多其他的字符串操作函数和方法,可以根据具体需求进行查阅。