python字符串如何遍历
时间: 2023-05-26 14:04:00 浏览: 51
Python中字符串可以使用for循环遍历,用法类似于列表,示例如下:
```python
s = 'hello'
for c in s:
print(c)
```
输出结果为:
```
h
e
l
l
o
```
也可以使用索引遍历字符串,示例如下:
```python
s = 'hello'
for i in range(len(s)):
print(s[i])
```
输出结果也为:
```
h
e
l
l
o
```
相关问题
python for循环遍历字符串数组
当我们需要遍历一个字符串数组时,可以使用Python的for循环结构来实现。下面是一个示例代码:
```python
str_array = ["hello", "world", "python"]
for str in str_array:
print(str)
```
在上述代码中,我们定义了一个字符串数组`str_array`,然后使用for循环遍历该数组。在每次循环中,将数组中的元素赋值给变量`str`,然后通过`print()`函数打印出来。
输出结果为:
```
hello
world
python
```
这样就完成了对字符串数组的遍历。你可以根据实际需求在循环体内进行其他操作。
python遍历字符串
Python中可以使用循环来遍历字符串。例如,以下代码可以打印出字符串中的每一个字符:
```
string = "hello world"
for char in string:
print(char)
```
输出结果:
```
h
e
l
l
o
w
o
r
l
d
```
你也可以通过索引来访问字符串中的每个字符,例如:
```
string = "hello world"
for i in range(len(string)):
print(string[i])
```
输出结果与上面相同。注意,这里使用了`range(len(string))`来生成一个从0到字符串长度减1的整数序列,然后通过索引来访问字符串中的字符。