利用 Python 遍历字符串的多种技巧186


Python 提供了丰富的字符串操作功能,遍历字符串是其中最常见的任务之一。本文将介绍各种 Python 方法,帮助您有效地遍历字符串。

1. 逐个字符遍历

最直接的方法是使用 Python 的 for 循环逐个字符遍历字符串:
```python
str = "Hello World"
for char in str:
print(char)
```

输出:
H
e
l
l
o
W
o
r
l
d

2. 使用 range() 索引

range() 函数可生成一个数字序列,用来索引字符串中的字符:
```python
str = "Hello World"
for i in range(len(str)):
print(str[i])
```

输出相同。

3. enumerate() 同时获取索引和字符

enumerate() 函数将可迭代对象中的每个元素与索引值配对:
```python
str = "Hello World"
for idx, char in enumerate(str):
print(f"Index: {idx}, Character: {char}")
```

输出:
Index: 0, Character: H
Index: 1, Character: e
Index: 2, Character: l
Index: 3, Character: l
Index: 4, Character: o
Index: 5, Character: W
Index: 6, Character: o
Index: 7, Character: r
Index: 8, Character: l
Index: 9, Character: d

4. use in 运算符

in 运算符可检查字符串中是否存在特定字符:
```python
str = "Hello World"
if "o" in str:
print("String contains the character 'o'")
```

输出:
String contains the character 'o'

5. 使用 split() 分割字符串

split() 方法将字符串分割为一个列表,其中每个元素对应于原字符串中的一个单词或子串:
```python
str = "Hello, World!"
words = ()
print(words)
```

输出:
['Hello,', 'World!']

6. 使用 join() 连接字符串

join() 方法将可迭代对象中的元素连接成一个字符串:
```python
list1 = ['Hello', 'World', '!']
new_str = ' '.join(list1)
print(new_str)
```

输出:
Hello World !

7. 使用 find() 查找子串

find() 方法在字符串中查找指定子串,并返回其起始索引:
```python
str = "Hello World"
idx = ("World")
print(idx)
```

输出:
6

8. 使用 replace() 替换子串

replace() 方法将字符串中的指定子串替换为另一个子串:
```python
str = "Hello World"
new_str = ("World", "Universe")
print(new_str)
```

输出:
Hello Universe

9. 使用 strip() 去除空白

strip() 方法从字符串中去除前导和尾随空白:
```python
str = " Hello World "
new_str = ()
print(new_str)
```

输出:
Hello World

10. 使用 isupper() 检查大小写

isupper() 方法检查字符串是否全是大写:
```python
str = "HELLO WORLD"
print(()) # True
str = "hello world"
print(()) # False
```

输出:
True
False

11. 使用 lower() 和 upper() 转换大小写

lower() 和 upper() 方法分别将字符串转换为小写和大写:
```python
str = "Hello World"
new_str_lower = ()
new_str_upper = ()
print(new_str_lower) # hello world
print(new_str_upper) # HELLO WORLD
```

12. 使用 isalpha() 检查字母

isalpha() 方法检查字符串是否仅包含字母(不包括数字或空格):
```python
str = "Hello World"
print(()) # False
str = "HelloWorld"
print(()) # True
```

输出:
False
True

13. 使用 isdigit() 检查数字

isdigit() 方法检查字符串是否仅包含数字(不包括字母或空格):
```python
str = "12345"
print(()) # True
str = "123 Hello"
print(()) # False
```

输出:
True
False

14. 使用 startswith() 和 endswith() 检查前缀和后缀

startswith() 和 endswith() 方法分别检查字符串是否以特定子串开始或结束:
```python
str = "Hello World"
print(("Hello")) # True
print(("World")) # True
```

输出:
True
True

15. 使用 format() 进行格式化

format() 方法允许您使用占位符将其他对象插入到字符串中:
```python
name = "John"
age = 30
message = "Hello, my name is {} and I am {} years old".format(name, age)
print(message) # Hello, my name is John and I am 30 years old
```

2024-10-14


上一篇:Python字符串生成:从基础到高级

下一篇:Python 基本代码