Python String is immutable in nature. What does it mean? In C, C++, or Java, we can change the value of a string after initialization. It means String is mutable in these programming languages. In the case of Python, once we initialize a string it becomes final and we do not have the authority to change the string value. In Python, any function that manipulates string value returns a new string and we have to explicitly assign it to the string, unless, the string value won’t change. Let’s discuss how we can manipulate and remove the white spaces from a string in Python. There are two methods 1. strip() method 2. replace() method
Using the strip() method:
Python string has a built-in function named .strip(). This function removes all the whitespace (leading and trailing) from the string explicitly. We can perform the same thing applying by the lstrip() or rstrip() function instead.
is_a_string = " My name is John "
print(is_a_string.strip())
The sample string has whitespace in both starting and at the end of it. Applying the strip() function will remove those whitespaces and return the string as:
My name is John
Top comments (0)