Question

[Solved] Python strip() not working inside a function

I am trying to use strip() to trim off the space before and after a string. It works fine for

str1 = "  abdced "
str1.strip()

However when I use it inside a function, it is not working:

def func(str1):
    return str1.strip() 

print func("   abdwe ") 

It won’t trim off any space. Anyone can tell what’s happening? Thanks!

Solution #1:

strip is not an in-place method, meaning it returns a value which must be reassigned like so:

str1 = str1.strip() # the string is reassigned to the returned stripped string
Respondent: Malik Brahimi
Solution #2:

Three things I see.

First, you are not assigning the strip variable to anything, second you are trying to do this in a return.

The return should only have the variables you wish to return to be used in another function.

You can print from this function, but your return statement should not have any activity, only the variable to be returned.

Third, that print statement looks off to me. At the very least it isn’t how I would do the print.

def func(str1):
    str1 = "  abdced "

    str2 = str1.strip()

    print(str2)

    return str1, str2
The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Most Popular

To Top
India and Pakistan’s steroid-soaked rhetoric over Kashmir will come back to haunt them both clenbuterol australia bossier man pleads guilty for leadership role in anabolic steriod distribution conspiracy