python字符串之综合练习
时间: 2024-10-29 19:05:26 浏览: 36
Python字符串是一个序列,可以进行多种操作的练习。以下是几个常见的字符串操作综合示例:
1. **创建字符串**:
```python
str1 = "Hello, World!"
```
2. **访问单个字符**:
```python
print(str1[0]) # 输出 'H'
```
3. **长度计算**:
```python
print(len(str1)) # 输出 13
```
4. **切片(Slicing)**:
```python
print(str1[7:12]) # 输出 'World'
```
5. **连接字符串**:
```python
str2 = "Python"
print(str1 + " " + str2) # 输出 'Hello, World! Python'
```
6. **复制字符串**:
```python
copy_str = str1 * 2 # 输出 'Hello, World!Hello, World!'
```
7. **查找和替换**:
```python
print(str1.replace('World', 'Python')) # 输出 'Hello, Python!'
```
8. **字符串格式化**:
```python
name = "Alice"
age = 25
print(f"My name is {name} and I'm {age} years old.") # 输出 'My name is Alice and I'm 25 years old.'
```
9. **转换大小写**:
```python
print(str1.upper()) # 输出 'HELLO, WORLD!'
print(str1.lower()) # 输出 'hello, world!'
```
阅读全文