Converting a list to a string list python
I am starting to start Python, I canβt hang my head. How can I change for example a = [[1,2],[3,4],[5,6]]
to string format "12\n34\n56"
.
This is as far as I understood, but it goes to a new line with each number.
def change(a):
c = ""
for r in a:
for b in r:
c += str(b) + "\n"
return c
source to share
but it goes to a new line with every number
This is because you are adding a new line after each number, not after each sublist r
. If you want, you must add a new line instead:
c = ''
for r in a:
for b in r:
c += str(b)
c += '\n'
return c
But note that appending to a line is very inefficient, as it creates many intermediate lines. Typically, instead, you will create a list where you add your string parts, and then finally join that list to convert it to a single string:
c = []
for r in a:
for b in r:
c.append(str(b))
c.append('\n')
return ''.join(c)
And then you can also use list expressions to make it shorter in a few steps; first for the inner list:
c = []
for r in a:
c.extend([str(b) for b in r])
c.append('\n')
return ''.join(c)
And you can join this list comprehension first:
c = []
for r in a:
c.append(''.join([str(b) for b in r]))
c.append('\n')
return ''.join(c)
Then you can move the new line to the outer join and create a new list view for the outer list:
c = [''.join([str(b) for b in r]) for r in a]
return '\n'.join(c)
And at this point, you can also make it a single liner:
return '\n'.join([''.join([str(b) for b in r]) for r in a])
As Padraic pointed out in the comments, appending to a newline also prevents the line from having a trailing one \n
, which you would end up if you kept adding it in a loop. Otherwise, you could use str.rstrip('\n')
to get rid of it afterwards.
source to share