I have a string like this:
filenames = 'file_1, file2, file3\nfile4'
I want to replace whitespaces with no space and new line with comma
So far i have tried this:
file_name = re.sub(r"\s+", "", filenames, flags=re.UNICODE)
which is returning:
file_name = 'file_1,file2,file3file4'
but i want:
filenames = 'file1,file2,file3,file4'
Try this:
file_name = re.sub(r"[,\s]+", ",", filenames, flags=re.UNICODE)
There is a difference from your written requirements and your desired output.
Firstly you need to replace '\n' with ', ' so it looks like your desired output.
Secondly, you are saying you want whitespaces with no spaces but in your desired output there is still spaces.
This is a fix for '\n':
doc = 'file_1, file2, file3\nfile4'
doc = doc.replace('\n', ', ')
print(doc)
file_1, file2, file3, file4
If you want whitespaces with no spaces:
doc = doc.replace(' ', '')
print(doc)
file_1,file2,file3,file4
A non regex solution would be to split, trim and join, after replacing all \n
by ','
. This will prevent removing needed spaces (in example, if a filename contains a space)
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, [...])
will remove any empty string, if, in example, you have 'foo,bar,,hello\n\nworld'
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.