Reputation: 53
I have a list and a for loop:
myList = [“aa,bb,cc,dd”, “ee,ff,gg,hh”]
for item in myList:
print (“x: %s” % item)
The output looks like:
x: aa,bb,cc,dd
x: ee,ff,gg,hh
My desired output is:
x: aa
bb
cc
dd
x: ee
ff
gg
hh
Upvotes: 0
Views: 134
Reputation: 118
+1 to the answer above..Another way could look like this:
myList = ["aa,bb,cc,dd", "ee,ff,gg,hh"]
for item in myList:
first, *rest = item.split(",")
print ("x: %s" %first)
for r in rest:
print (" %s" %r)
Upvotes: 0
Reputation: 8326
you can use the split
and join
functions pretty seamlessly
>>> myList = ["aa,bb,cc,dd", "ee,ff,gg,hh"]
>>> for item in myList:
... print("x: %s" % "\n ".join(item.split(",")))
...
x: aa
bb
cc
dd
x: ee
ff
gg
hh
split
splits the string into a list based on the delimiter you pass as a parameter, and join
will join a list into a string, using the string you call it on as a joiner.
Another option would be to just use replace:
>>> for item in myList:
... print("x: %s" % item.replace(",", "\n "))
...
x: aa
bb
cc
dd
x: ee
ff
gg
hh
Upvotes: 1