📜  在Python中迭代字符的字符串

📅  最后修改于: 2022-05-13 01:55:50.915000             🧑  作者: Mango

在Python中迭代字符的字符串

在Python中,使用 String 进行操作时,可以对其进行多项操作。让我们看看如何在Python中迭代字符的字符串。

示例 #1:使用简单的迭代和range()

# Python program to iterate over characters of a string
  
# Code #1
string_name = "geeksforgeeks"
  
# Iterate over the string
for element in string_name:
    print(element, end=' ')
print("\n")
  
  
# Code #2
string_name = "GEEKS"
  
# Iterate over index
for element in range(0, len(string_name)):
    print(string_name[element])
输出:
g e e k s f o r g e e k s 

G
E
E
K
S


示例 #2:使用enumerate()函数

# Python program to iterate over characters of a string
  
string_name = "Geeks"
  
# Iterate over the string
for i, v in enumerate(string_name):
    print(v)
输出:
G
e
e
k
s


示例#3:以相反的顺序迭代字符

# Python program to iterate over characters of a string
  
# Code #1
string_name = "GEEKS"
  
# slicing the string in reverse fashion 
for element in string_name[ : :-1]:
    print(element, end =' ')
print('\n')
  
# Code #2
string_name = "geeksforgeeks"
  
# Getting length of string
ran = len(string_name)
  
# using reversed() function
for element in reversed(range(0, ran)):
    print(string_name[element])
输出:
S K E E G 

s
k
e
e
g
r
o
f
s
k
e
e
g


示例#4:对特定元素集的迭代。

通过传递特定的字符串索引值对string_name执行迭代。

# Python program to iterate over particular set of element.
string_name = "geeksforgeeks"
  
# string_name[start:end:step]
for element in string_name[0:8:1]: 
    print(element, end =' ')
输出:
g e e k s f o r