如何删除python3中字符串的“\n”?

2024-10-04 07:32:08 发布

您现在位置:Python中文网/ 问答频道 /正文

if __name__ == '__main__':
    string =[' \n            Boeing Vancouver\n          ', '\n          Airbus\n        ', '\n          Lockheed Martin\n        ', '\n          Rolls-Royce\n        ', '\n          Northrop Grumman\n        ', '\n          BOMBARDIER\n        ', '\n          Raytheon\n        ']
    for item in string:
        item.replace("\n"," ")
        item.strip()
    print(string)

输出和输入是一样的,为什么?你知道吗


Tags: namestringifmainitemmartinrollsbombardier
3条回答

您可以使用list comprehension,例如:

代码:

[s.replace("\n", " ") for s in a_string]

测试代码:

a_string = [' \n            Boeing Vancouver\n          ',
          '\n          Airbus\n        ',
          '\n          Lockheed Martin\n        ',
          '\n          Rolls-Royce\n        ',
          '\n          Northrop Grumman\n        ',
          '\n          BOMBARDIER\n        ',
          '\n          Raytheon\n        ']


print([s.replace("\n", " ") for s in a_string])

结果:

['              Boeing Vancouver           ', 
 '           Airbus         ', 
 '           Lockheed Martin         ', 
 '           Rolls-Royce         ', 
 '           Northrop Grumman         ', 
 '           BOMBARDIER         ', 
 '           Raytheon         ']

字符串在python中是不可修改的。您可以使用列表理解简单地去掉前导或尾随的空格来创建新的列表。你知道吗

[x.strip() for x in string]

您需要再次查看the documentation

Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.

换句话说,item.replace("\n"," ")本身什么也不做。你知道吗

相关问题 更多 >