Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove whitespace from end of string in Python?

I want to remove the whitespace at the end of 'Joe'

name = 'Joe'
print(name, ', you won!')
>>>Joe , you won!

I tried the rstrip method, but it didn't work

name='Joe'
name=name.rstrip()
print(name, ', you won!')
>>>Joe , you won!

My only solution was to concatenate the string

name='Joe'
name=name+','
print(name,'you won!')
>>>Joe, you won!

What am I missing?

like image 245
theBIOguy Avatar asked Mar 03 '14 17:03

theBIOguy


People also ask

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

The String. trim() method # You can call the trim() method on your string to remove whitespace from the beginning and end of it. It returns a new string.

How do I remove a trailing character in Python?

Python String rstrip() Method The rstrip() method removes any trailing characters (characters at the end a string), space is the default trailing character to remove.

How do I remove a suffix in Python?

Method #1 : Using loop + remove() + endswith() Method.


1 Answers

The print() function adds whitespace between the arguments, there is nothing to strip there.

Use sep='' to stop the function from doing that:

print(name, ', you won!', sep='')

or you can use string formatting to create one string to pass to print():

print('{}, you won!'.format(name))
like image 72
Martijn Pieters Avatar answered Sep 27 '22 23:09

Martijn Pieters