在 Python 中迴圈遍歷字串

Shivam Arora 2023年1月30日
  1. 在 Python 中使用 for 迴圈迴圈遍歷字串
  2. 在 Python 中使用 while 迴圈迴圈遍歷字串
在 Python 中迴圈遍歷字串

字串是一串字元,其中每個字元都位於特定索引處,可以單獨訪問。

在本教程中,我們遍歷一個字串並在 Python 中列印單個字元。

在 Python 中使用 for 迴圈迴圈遍歷字串

for 迴圈用於迭代列表、字串等結構。字串本質上是可迭代的,這意味著對字串的迭代將每個字元作為輸出。

例如,

for i in "String":
    print(i)

輸出:

S
t
r
i
n
g

在上面的例子中,我們可以使用迭代器 i 直接訪問字串中的每個字元。

或者,我們可以使用字串的長度並根據其索引訪問字元。

例如,

Str_value = "String"
for index in range(len(Str_value)):
    print(Str_value[index])

輸出:

S
t
r
i
n
g

enumerate() 函式可用於字串。它用於保持迴圈中執行的迭代次數的計數。它通過向可迭代物件新增一個計數器來實現。它返回一個包含可以迴圈的元組列表的物件。

例如,

for i, j in enumerate("string"):
    print(i, j)

輸出:

0 s
1 t
2 r
3 i
4 n
5 g

在 Python 中使用 while 迴圈迴圈遍歷字串

對於給定的語句集,while 迴圈的使用就像 for 迴圈一樣,直到給定的條件為 True。我們使用 len() 函式提供字串的長度以迭代字串。

在 while 迴圈中,上限作為字串的長度傳遞,從頭開始遍歷。
迴圈從字串的第 0 個索引開始,直到最後一個索引並列印每個字元。

例如,

Str_value = "String"
i = 0
while i < len(Str_value):
    print(Str_value[i])
    i = i + 1

輸出:

S
t
r
i
n
g

相關文章 - Python String