Answer to Question #95269 in Python for Vivek Kumar

Question #95269
Which function would you choose to use to remove leading and trailing white spaces from a given string
1
Expert's answer
2019-09-26T14:34:29-0400

If you need to remove exclusively all extra spaces from the beginning and from the end, you can use the method:

string.strip()

>>>x = "   Something      string       "
>>>x.strip()
>>>"Something      string"


If you need to remove all extra spaces from string, you can use two methods:

strip and split()

>>> x = "      Something \n\n  string    \n\n"
>>> " ".join(x.strip().split())
>>> "Something string"

If you need your own code, you can use this functions:

def delete_white_space(string):
    begin, end = 0,0
    check_b, check_e = False, False
    for i in range(len(string)):
        if string[i] not in [' ', '\n', '\r'] and not check_b:
            begin = i
            check_b = True
        if string[len(string)-1-i] not in [' ', '\n', '\r'] and not check_e:
            end = len(string)-1-i
            check_e = True
        if check_e and check_b:
            break
    return string[begin:end+1]

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS