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]
Comments
Leave a comment