Function equivalent to Trim (function to remove extra spaces at the beginning and end) in Python?

Asked

Viewed 42,959 times

14

In PHP and Javascript, we have the function trim that serves to trim a string, removing extra spaces at the beginning and end.

Thus:

 $str = ' meu nome é wallace ';
 var_dump(trim($str)); // string('meu nome é wallace')

How can I do that in Python?

I couldn’t find any function like trim.

  • 1

    print "".Join(cell.Encode('utf-8').strip().Lower().split() use this function to remove the ""

  • 1

    It seems a lot of operation for a simple thing @Guilhermelima

  • why he really does so much, utf8, lowercase...

  • 1

    Is this setar utf8 thing necessary in python? It’s like PHP stuff (I have nothing against php, I love it :D)

  • @Wallacemaxters everything in Python is Unicode by default. To tell you the truth, I don’t think.

  • in reality not precise, it was a specific situation.

Show 1 more comment

5 answers

18


.strip

According to the manual, there is the method .strip():

minhaString.strip()

If you need to specify the characters to be removed, such as spaces only, leaving tabs and line breaks, you can use:

minhaString.strip(" ")

Note that in this second case, if you specify multiple characters, they are treated individually:

"tomate seco".strip("otm")

Return:

ate sec


.rstrip and . lstrip

If you need to remove only on the left, you have the .lstrip():

"banana".lstrip( "abc" )

Return:

nana

and if you need to remove only to the right, you have the .rstrip():

"banana".lstrip( "a" )

Return:

banan

The default of .rstrip and of .lstrip also is to remove spacing characters such as tabulations and line breaks.


Deprecated

For the record, this existed as a function:

string.strip( string [, caracteres] )

It worked in the same way as described above, but the string was the first argument of the call, and the second optional, the characters to be removed. Similarly, if omitted, it referred to blank spaces, tabulations and line breaks.

I am referring to myself in the past, but it will work until it is actually removed.

  • Your answer is also important. In PHP you have the ltrim and rtrim, right and left. + 1

11

It has no function under the name of trim() but has the strip() that does the equivalent job. It removes the characters \n, \r, \t, \f, espaço

" meu nome é wallace ".strip()

Based on: Trimming a string in Python

  • Faster than @Bacco and the meteors of Pégasus

  • 2

    Yeah. I only restored mine because of lstrip, but on the strip "dry" @rray won. And already upetb.

  • 1

    You just can’t say that @rray or I are good at . strip, otherwise it’s gonna sound a little weird.

  • 1

    hahaha @Bacco, this applies only to strings :P.

  • 1

    as long as they don’t think G-strings is fine :D

5

What you seek is the .strip(). It is responsible for removing spaces at the beginning and end, such as the trim().

' meu nome é wallace '.strip()

You have other options, such as .replace().

str= ' meu nome é wallace '
str.replace(" ", "")

Remembering that this way will remove all, not only the beginning and end, as the trim.

Also remembering that in python also has .rstrip() and .lstrip(), for removing characters on the right and left, respectively.

How the question is about PHP > Python, there is the site php2python exactly for this.

Sources:
Trimming a string in Python
How to Trim whitespace (including tabs)? Python Manual

3

Complementing.

To remove all blanks you can use the join and the split as suggested in the comments by Guilherme Lima, take the example:

s = " Stack Over Flow "
s = ''.join(s.split())

print s

Exit:StackOverFlow

Or a regular expression:

import re

s = " Stack Over Flow "    
pattern = re.compile(r'\s+')    
s = re.sub(pattern, '', s)    
print s

Exit: StackOverFlow

And to remove only whitespace at the beginning and end of the string use the strip as suggested by users rray, Bacchus and Randrade:

s = " Stack Over Flow "

s = s.strip()

print s

Exit: Stack Over Flow

See the module documentation re to learn more.
See the documentation regarding common string operations to learn more about the commands join, split and strip.

Source:
Python remove all whitespace in a string

2

To make a python Trim function that serves to trim string, removing extra spaces at the beginning and end, just use Regular Expression indicating white space at the end (r' s+$') and at the beginning of String (r' s+'), see:

Input: "Stack Over Flow "

import re

s = " Stack Over Flow "
print "'"+s+"'"
pattern = re.compile(r'\s+$')    
s = re.sub(pattern, '', s)
pattern = re.compile(r'^\s+')
s = re.sub(pattern, '', s)
print "'"+s+"'"

Output: "Stack Over Flow"

Browser other questions tagged

You are not signed in. Login or sign up in order to post.