Цикл while в Python со строками: методы и примеры

Вот несколько способов реализации цикла while со строкой в ​​Python:

  1. Базовый цикл while:

    string = "Hello, world!"
    index = 0
    while index < len(string):
    print(string[index])
    index += 1
  2. Цикл с условием:

    string = "Hello, world!"
    index = 0
    while index < len(string):
    if string[index] == "o":
        print("Found 'o' at index", index)
    index += 1
  3. Бесконечный цикл с оператором прерывания:

    string = "Hello, world!"
    index = 0
    while True:
    if index >= len(string):
        break
    print(string[index])
    index += 1
  4. Цикл с завершением пользовательского ввода:

    string = ""
    while string != "quit":
    string = input("Enter a string (or 'quit' to exit): ")
    print("You entered:", string)
  5. Цикл с манипулированием строками:

    string = "Hello, world!"
    index = 0
    while index < len(string):
    if string[index].isalpha():
        print(string[index].upper())
    index += 1