1. 程式人生 > >去掉字串中空格的四種方法

去掉字串中空格的四種方法

方法一:

def remove_space(text):
   return ''.join([i for i in text if i!=' '])
print(remove_space('hello my name is fang'))

方法二:

string='hello my name is fang'
print(string.replace(' ',''))

方法三:

def remove_space1(text):
    result=''
    for i in text:
        if i!=' ':
            result+=i
    return
result if __name__=='__main__': print(remove_space1('hello my name is xiao ming'))

第四種:應用生成器

def remove_space2(text):
    for char in text:
        if char!=' ':
            yield char

result=remove_space2('wo zai shi yong sheng cheng qi')
ss=''
for i in result:
    ss+=i
print(ss)