Вот несколько способов реализации цикла while со строкой в Python:
-
Базовый цикл while:
string = "Hello, world!" index = 0 while index < len(string): print(string[index]) index += 1
-
Цикл с условием:
string = "Hello, world!" index = 0 while index < len(string): if string[index] == "o": print("Found 'o' at index", index) index += 1
-
Бесконечный цикл с оператором прерывания:
string = "Hello, world!" index = 0 while True: if index >= len(string): break print(string[index]) index += 1
-
Цикл с завершением пользовательского ввода:
string = "" while string != "quit": string = input("Enter a string (or 'quit' to exit): ") print("You entered:", string)
-
Цикл с манипулированием строками:
string = "Hello, world!" index = 0 while index < len(string): if string[index].isalpha(): print(string[index].upper()) index += 1