Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I remove whitespace from the end of a string in Python?

Tags:

python

People also ask

How do I remove whitespace at the end of a string in Python?

strip() Python String strip() function will remove leading and trailing whitespaces. If you want to remove only leading or trailing spaces, use lstrip() or rstrip() function instead.

How do you remove whitespace at the end of a string?

String result = str. trim(); The trim() method will remove both leading and trailing whitespace from a string and return the result.

What is the best way to remove whitespace characters from the start or end in Python?

The Python String strip() method is part of the built-in function available in python. The function will remove given characters from the start and end of the original string. This function is very helpful in removing the whitespaces at the start and end of the given string, as shown in the example.

How do you the remove the whitespace at the end of the output?

use printf(" %d",a[i][j]). Simply put space before rather than after. You can use \b for backspace as well.


>>> "    xyz     ".rstrip()
'    xyz'

There is more about rstrip in the documentation.


You can use strip() or split() to control the spaces values as the following, and here is some test functions:

words = "   test     words    "

# Remove end spaces
def remove_end_spaces(string):
    return "".join(string.rstrip())

# Remove first and  end spaces
def remove_first_end_spaces(string):
    return "".join(string.rstrip().lstrip())

# Remove all spaces
def remove_all_spaces(string):
    return "".join(string.split())

# Remove all extra spaces
def remove_all_extra_spaces(string):
    return " ".join(string.split())

# Show results
print(f'"{words}"')
print(f'"{remove_end_spaces(words)}"')
print(f'"{remove_first_end_spaces(words)}"')
print(f'"{remove_all_spaces(words)}"')
print(f'"{remove_all_extra_spaces(words)}"')

output:

"   test     words    "

"   test     words"

"test     words"

"testwords"

"test words"

i hope this helpful .