""" Урок 20. Методы строк — весь код примеров одним файлом. Источник: subjects/python-fundamentals/course/lessons/20-string-methods/examples.html Файл собран автоматически (tools/build_lesson_examples.py): правьте страницу урока. Запуск: python lesson-20.py """ # ==================================================================== # Пример 1: методы регистра # ==================================================================== text = "Hello, worlD!" print(text.upper()) # HELLO, WORLD! print(text.lower()) # hello, world! print(text.capitalize()) # Hello, world! print(text.title()) # Hello, World! print(text.swapcase()) # hELLO, WORLd! # ==================================================================== # Пример 2: поиск подстроки # ==================================================================== text = "Python is awesome. Python is dynamic." print(text.find("Python")) # 0 print(text.rfind("Python")) # 19 print(text.find("Java")) # -1 print(text.count("Python")) # 2 print(text.count("is")) # 2 # Безопасная проверка через find if text.find("Java") != -1: print("Java найдена") else: print("Java не найдена") # ==================================================================== # Пример 3: замена и разделение # ==================================================================== text = "I love Python, Python is great" new_text = text.replace("Python", "Java") print(new_text) fruits = "apple,banana,cherry" print(fruits.split(",")) multi = "apple---banana---cherry" print(multi.split("---", 1)) # ==================================================================== # Пример 4: split() против split(" ") # ==================================================================== text = "apple banana\t cherry\n" print(text.split()) # ['apple', 'banana', 'cherry'] print(text.split(" ")) # ['apple', '', '', '', '', 'banana\t', 'cherry\n'] # ==================================================================== # Пример 5: очистка строки от лишних символов # ==================================================================== raw = "\t hello world\n " print(f"[{raw.strip()}]") stars = "***hello***" print(stars.strip("*")) mixed = "**--*hello---***" print(mixed.strip("*-")) # ==================================================================== # Пример 6: проверка содержимого строки # ==================================================================== print("Hello".isalpha()) # True print("Python3".isalpha()) # False print("12345".isdigit()) # True print("12345.1".isdigit()) # False print("Hello World".istitle()) # True print("hello world".startswith("he")) # True print("hello world".endswith("ld")) # True # ==================================================================== # Пример 7: объединение списка строк # ==================================================================== words = ["Python", "is", "awesome"] print(" ".join(words)) print("-".join(words)) print("".join(words)) # Создание CSV-строки из списка чисел numbers = [1, 2, 3, 4] csv = ",".join(str(n) for n in numbers) print(csv) # ==================================================================== # Пример 8: звёздочки вместо цифр # ==================================================================== text = "My number is 123-456-789" result = "" for char in text: if char.isdigit(): result += "*" else: result += char print(f"Строка: {text}") print(f"Результат: {result}") # ==================================================================== # Пример 9: повторяющиеся символы # ==================================================================== text = "Programming in python" lowered = text.lower() seen = set() print(f"Строка: {text}") for char in lowered: if char not in seen and lowered.count(char) > 1: print(f"Символ '{char}' встречается {lowered.count(char)} раз(а)") seen.add(char) # ==================================================================== # Пример 10: числа в строке, умноженные на 10 # ==================================================================== text = "I have 5 apples and 10 oranges, price is 0.5 each. Card number is ....3672." new_words = [] for word in text.split(): try: number = float(word) new_words.append(str(number * 10)) except ValueError: new_words.append(word) print(" ".join(new_words)) # ==================================================================== # Пример 11: выравнивание строк и удаление префикса/суффикса # ==================================================================== label = "42" print(label.zfill(5)) # 00042 print("Py".center(10, "-")) # ----Py---- print("Py".ljust(10, ".")) # Py........ print("Py".rjust(10, ".")) # ........Py filename = "lesson_20_string_methods.py" print(filename.removesuffix(".py")) # lesson_20_string_methods print(filename.removeprefix("lesson_20_")) # string_methods.py