0

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

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

No problem anytime !
0

+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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.