Удаление пробелов из строки в Python

Чтобы удалить пробелы из строки в Python, вы можете использовать несколько методов. Вот несколько примеров:

Метод 1: использование функции replace()

string = "Hello World"
string_without_spaces = string.replace(" ", "")
print(string_without_spaces)

Выход:

HelloWorld

Метод 2: использование функций Split() и join()

string = "Hello World"
string_without_spaces = "".join(string.split())
print(string_without_spaces)

Выход:

HelloWorld

Метод 3: использование понимания списка и метода join()

string = "Hello World"
string_without_spaces = "".join([char for char in string if char != " "])
print(string_without_spaces)

Выход:

HelloWorld

Метод 4. Использование регулярных выражений (перемодуль)

import re
string = "Hello World"
string_without_spaces = re.sub(r"\s+", "", string)
print(string_without_spaces)

Выход:

HelloWorld