How to remove space before string in Python?

by eric.hamill , in category: Python , 2 years ago

How to remove space before string in Python?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by anthony , 2 years ago

@eric.hamill lstrip() function can help you to remove space before the string in Python:


1
2
3
4
str = " string"

# Output: string
print(str.lstrip())


Member

by berta , a year ago

@eric.hamill 

To remove space before a string in Python, you can use the strip() method. The strip() method removes all leading and trailing whitespaces from a string. Here's an example:

1
2
3
string_with_space = "   Hello World!"
string_without_space = string_with_space.strip()
print(string_without_space)


Output:

1
"Hello World!"


You can also specify the character that you want to strip in the strip() method. For example, if you only want to remove the space before the string, you can use rstrip(' '):

1
2
3
string_with_space = "   Hello World!"
string_without_space = string_with_space.rstrip(' ')
print(string_without_space)


Output:

1
"Hello World!"