I have a string as such:
teststring = 'Index: WriteVTKOutput.FOR\\r\\n======================================\\r\\n'
I'd like to split it based on the '\\\\r'
and '\\\\n'
characters, such that I get the following result:
testlist = ['Index: WriteVTKOutput.FOR', '======================================']
I tried the following commands, none of which worked:
teststring.split(r'\r\n')
teststring.splitlines()
How does a man split that string into those delimiters while retaining his dignity and keeping it real?
Thanks
这应该做的工作:
lst = teststring.split("\\r\\n")[:-1]
splitlines
won't work because your separators aren't really line separators. They're just the actual \\r\\n
chars.
You can get rid of trailing/leading empty fields that split
generates by an extra comprehension in case your string starts or ends by r"\\r\\n"
:
[x for x in teststring.split(r'\r\n') if x]
result:
['Index: WriteVTKOutput.FOR', '======================================']
teststring = 'Index: WriteVTKOutput.FOR\\r\\n======================================\\r\\n'
print(teststring.split("\\r\\n")[:-1])
print(teststring.strip("\\r\\n").split("\\r\\n"))
Output
['Index: WriteVTKOutput.FOR', '======================================']
['Index: WriteVTKOutput.FOR', '======================================']
You need : '\\\\r\\\\n'
or r'\\r\\n'
teststring = 'Index: WriteVTKOutput.FOR\\r\\n======================================\\r\\n'
new_string = [x for x in teststring.split('\\r\\n') if x]
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.