Trying to split a multiline paragraph using str.split single line split works correctly. Is str.split the correct way to split multiple lines what am I missing here? single line split working correctly example:
dmap_lines = """Nople Normal Altar1-truck-Altar2,Altar2-train-Cansomme,Cansomme-flight-Karoh,Karoh-truck-Nople"""
destinations = []
remainders1 = []
stages = []
for line in dmap_lines:
destination, remainder1, remainder = dmap_lines.split(' ')
destinations.append(destination)
remainders1.append(remainder1)
remainder = remainder.split(',')
stages.append(remainder)
print(destination)
print(remainder1)
print(type(remainder))
print(remainder)
Expected Output:
Nople
Normal
<class 'list'>
['Altar1-truck-Altar2', 'Altar2-train-Cansomme', 'Cansomme-flight-Karoh', 'Karoh-truck-Nople']
with multiline code:
dmap_lines = """Nople Normal Altar1-truck-Altar2,Altar2-train-Cansomme,Cansomme-flight-Karoh,Karoh-truck-Nople\nDria Normal Altar1-truck-Altar2,Altar2-train-Mala1,Mala1-truck-Mala2,Mala2-flight-Dria"""
destinations = []
remainders1 = []
stages = []
for line in dmap_lines:
destination, remainder1, remainder = dmap_lines.split(' ')
destinations.append(destination)
remainders1.append(remainder1)
remainder = remainder.split(',')
stages.append(remainder)
print(destination)
print(remainder1)
print(type(remainder))
print(remainder)
Receiving error in output:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-78-9eb9f8fa1c64> in <module>
4 stages = []
5 for line in dmap_lines:
----> 6 destination, remainder1, remainder = dmap_lines.split(' ')
7 destinations.append(destination)
8 remainders1.append(remainder1)
ValueError: too many values to unpack (expected 3)
Expected output:
Nople
Normal
<class 'list'>
['Altar1-truck-Altar2', 'Altar2-train-Cansomme', 'Cansomme-flight-Karoh', 'Karoh-truck-Nople']
Dria
Normal
<class 'list'>
['Altar1-truck-Altar2,Altar2-train-Mala1,Mala1-truck-Mala2,Mala2-flight-Dria']
Why is the for loop not iterating over multiple lines and splitting the string into the sections?
Is there any reason why re.findall
would not be a better approach here:
dmap_lines = "Nople Normal Altar1-truck-Altar2,Altar2-train-Cansomme,Cansomme-flight-Karoh,Karoh-truck-Nople"
matches = re.findall(r'\b\w+-\w+-\w+\b', dmap_lines)
print(matches)
This prints:
['Altar1-truck-Altar2', 'Altar2-train-Cansomme', 'Cansomme-flight-Karoh',
'Karoh-truck-Nople']
To get a single CSV string, use join
:
csv = ','.join(matches)
print(csv)
This prints:
Altar1-truck-Altar2,Altar2-train-Cansomme,Cansomme-flight-Karoh,Karoh-truck-Nople
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.