""" Урок 14. Знакомство со строками — весь код примеров одним файлом. Источник: subjects/python-fundamentals/course/lessons/14-python-strings-intro/examples.html Файл собран автоматически (tools/build_lesson_examples.py): правьте страницу урока. Запуск: python lesson-14.py """ # ==================================================================== # Пример 1. Создание строк: кавычки, тройные строки, тип str # ==================================================================== single = 'Hello' double = "Hello" multi = """First line Second line""" empty = "" print(single) # Hello print(double) # Hello print(multi) # First line # Second line print(repr(empty)) # '' print(type(single)) # print(len(single), len(multi)) # 5 22 # ==================================================================== # Пример 2. Неизменяемость строк # ==================================================================== s = "Hello" print(id(s)) # 2171595019120 (адрес будет другим при каждом запуске) s2 = s + " world!" print(s) # Hello — исходная строка не изменилась print(s2) # Hello world! print(id(s2)) # 2171597817904 — другой объект print(s is s2) # False try: s[0] = "h" except TypeError as error: print("TypeError:", error) # 'str' object does not support item assignment # ==================================================================== # Пример 3. Индексация строк # ==================================================================== text = "Python" print(text[0]) # P print(text[2]) # t print(text[-1]) # n print(text[-3]) # h index = 10 if index < len(text): print(text[index]) else: print("Index out of range") # Index out of range try: print(text[10]) except IndexError as error: print("IndexError:", error) # string index out of range # ==================================================================== # Пример 4. Срезы строк # ==================================================================== text = "Python programming" print(text[0:6]) # Python print(text[:6]) # Python — с начала строки print(text[7:]) # programming — до конца строки print(text[:]) # Python programming — копия всей строки print(text[-11:]) # programming — отрицательный индекс print(text[0:12:2]) # Pto rg — с шагом 2 print(text[::-1]) # gnimmargorp nohtyP — разворот строки print(repr(text[14:7])) # '' — start после end: пустая строка, не ошибка print(repr(text[-4:-11])) # '' # ==================================================================== # Пример 5. Конкатенация и повторение # ==================================================================== first = "Py" second = "thon" print(first + second) # Python print("=" * 10) # ========== print("ab" * 3) # ababab line = "-" * 20 print(line) # -------------------- # ==================================================================== # Пример 6. Escape-последовательности и raw-строки # ==================================================================== text = "Line 1\nLine 2\tTabbed" print(text) # Line 1 # Line 2 Tabbed quote = 'It\'s ok' print(quote) # It's ok path = r"C:\Users\Admin\file.txt" print(path) # C:\Users\Admin\file.txt — слэши не экранируются print("Backslash: \\") # Backslash: \ # ==================================================================== # Пример 7. len(), ord(), chr() и кодировка UTF-8 # ==================================================================== text = "Python" print(len(text)) # 6 print(len("")) # 0 print(ord("A")) # 65 print(ord("a")) # 97 print(chr(65)) # A print(chr(97)) # a text_ru = "Привет" encoded = text_ru.encode("utf-8") print(encoded) # b'\xd0\x9f\xd1\x80\xd0\xb8\xd0\xb2\xd0\xb5\xd1\x82' decoded = encoded.decode("utf-8") print(decoded) # Привет # ==================================================================== # Пример 8. Оператор in и перебор строки в цикле # ==================================================================== text = "Python programming" print("Python" in text) # True print("Hello" in text) # False print("Java" not in text) # True phrase = "Hello, World!" vowels = "aeiou" count = 0 for char in phrase.lower(): if char in vowels: count += 1 print(f"Vowels: {count}") # Vowels: 3 symbol = "o" count2 = 0 for char in phrase: if char == symbol: count2 += 1 print(f"Symbol '{symbol}' appears {count2} time(s).") # Symbol 'o' appears 2 time(s). print(phrase.count(symbol)) # 2 — то же самое встроенным методом # ==================================================================== # Пример 9. f-строки — современный способ подставить значения # ==================================================================== name = "Alice" age = 30 print(f"Hello, {name}! Next year you will be {age + 1}.") # Hello, Alice! Next year you will be 31. pi = 3.14159265 print(f"Pi rounded: {pi:.2f}") # Pi rounded: 3.14 # ==================================================================== # Пример 10. Базовые строковые методы # ==================================================================== raw = " Hello, Python! " print(repr(raw.strip())) # 'Hello, Python!' print(raw.upper()) # " HELLO, PYTHON! " print(raw.lower()) # " hello, python! " print(raw.replace("Python", "World")) # " Hello, World! " print(raw.find("Py")) # 9 print(raw.startswith(" He")) # True print(raw.split(", ")) # [' Hello', 'Python! '] print(raw) # " Hello, Python! " — исходная строка не изменилась # ==================================================================== # Пример 11. Задача из лекции: палиндром # ==================================================================== def check_palindrome(value): return value == value[::-1] for sample in ("radar", "hello"): result = "The string is a palindrome" if check_palindrome(sample) else "The string is not a palindrome" print(f"{sample!r}: {result}") # 'radar': The string is a palindrome # 'hello': The string is not a palindrome # ==================================================================== # Пример 12. Задача из лекции: дешифровка шифра Цезаря # ==================================================================== def caesar_decrypt(encrypted_text, shift): decrypted_text = "" i = 0 while i < len(encrypted_text): char = encrypted_text[i] decrypted_char = chr(ord(char) - shift) decrypted_text += decrypted_char i += 1 return decrypted_text print(caesar_decrypt("khoor", 3)) # hello