Here are ways to trim(remove) whitespaces from a string in Python:
Whitespace includes all Unicode whitespace characters, such as spaces, tabs (\t), carriage returns (\r), and newlines (\n).
Method 1: Using strip()
The strip() method is used to remove leading and trailing whitespaces.
Visual Representation
Example
my_string = " Lee Kuan Yew "
print(my_string)
print(my_string.strip())
Output
Lee Kuan Yew
Lee Kuan Yew
Method 2: Using lstrip()
The lstrip() method is used to remove all leading(left-side) whitespaces.
Visual Representation
Example
my_string = " Lee Kuan Yew "
print(my_string)
print(my_string.lstrip())
Output
Lee Kuan Yew
Lee Kuan Yew
Method 3: Using rstrip()
The rstrip() method is used to remove all trailing(right-side) whitespaces.
Visual Representation
Example
my_string = " Lee Kuan Yew "
print(my_string)
print(my_string.rstrip())
Output
Lee Kuan Yew
Lee Kuan Yew
Tip: Sometimes, when code is in production mode, coders use the regular expression method re.sub(), which can handle more complex patterns of whitespace.
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.