用逗号替换空格和新行

2024-09-28 22:31:27 发布

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

我有这样一个字符串:

filenames = 'file_1, file2, file3\nfile4'

我想用空格代替空格,用逗号代替新行

到目前为止,我已经尝试过:

file_name = re.sub(r"\s+", "", filenames, flags=re.UNICODE)

它正在返回:

file_name = 'file_1,file2,file3file4'

但我想:

filenames = 'file1,file2,file3,file4'

Tags: 字符串namereunicodefile1file2fileflags
3条回答

非正则表达式的解决方案是在用','替换所有\n之后进行拆分、修剪和连接。这将阻止删除所需的空格(例如,如果文件名包含空格)

filenames = 'file_1, file2, file3\nfile4, file         5'
','.join(filter(None, [s.strip() for s in filenames.replace('\n', ',').split(',')]))
# 'file_1,file2,file3,file4,file         5'

filter(None, [...])将删除任何空字符串,例如,如果您有'foo,bar,,hello\n\nworld'

这与您的书面需求和期望的输出不同

首先,您需要将“\n”替换为“,”,使其看起来像您想要的输出

第二,你说你想要没有空格的空白,但是在你想要的输出中仍然有空格

这是对“\n”的修复:

doc = 'file_1, file2, file3\nfile4'
doc = doc.replace('\n', ', ')
print(doc)
file_1, file2, file3, file4

如果需要不带空格的空白:

doc = doc.replace(' ', '')
print(doc)
file_1,file2,file3,file4

试试这个:

file_name = re.sub(r"[,\s]+", ",", filenames, flags=re.UNICODE)

相关问题 更多 >