下面python代码里面的第二个和第三个函数都能实现题目的功能,第二个使用了系统的正则库。第一个函数是删除字符串中所有空格。
def remove_all_blank(ss):
'''
delete all blank in string ss
:param ss:
:return:
'''
#empty string or None
if not ss or len(ss) == 0:
return ''
letters = list(ss)
i = 0
for j in range(len(letters)):
if letters[j] != ' ':
letters[i] = letters[j]
i = i + 1
else:
pass
return ''.join(letters[0:i])
def remove_redundant_blank_with_re(string):
'''
remove blank at the beginning and end of string, compress successive blanks into one blank in the middle of string
:param string:
:return:
'''
string = string.strip()
import re
sub_string = re.split('[ ]+', string)
return ' '.join(sub_string)
def remove_redundant_blank2(string):
'''
remove blank at the beginning and end of string, compress successive blanks into one blank in the middle of string
:param string:
:return:
'''
first = True
letters = []
for s in string:
if s != ' ':
letters.append(s)
first = True
elif s == ' ' and first:
letters.append(s)
first = False
else:
pass
#delete blank in front of string
if letters[0] == ' ':
if len(letters) > 1:
letters = letters[1:]
else:
return []
#delete blank at the end of string
if letters[-1] == ' ':
del letters[-1]
return letters
if __name__ == '__main__':
print(remove_all_blank(" "))
print(remove_redundant_blank2(" a "))