Python: why extra spaces when printing an unpacked lterable? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Python: why extra spaces when printing an unpacked lterable?

I was working on code for a string diamond in as few lines as possible (if anybody is interested: https://code.sololearn.com/cLT5P34UQwH8) However, when trying different ways to print lists of strings line-by-line, I found that unpacking a list into a print function with an asteriks creates extra spaces at the beginning of a new line. This was an issue when printing my string diamonds. I fixed it now by using another printing method but I still do not understand the origin of these extra spaces. Here a comparison of three methods I used: https://code.sololearn.com/cDlm9rQA2npw Can anybody explain to me where the spaces in method 3 come from?

21st Apr 2020, 8:43 PM
Froggy
Froggy - avatar
7 Answers
+ 2
unpacking creates extra spacing. Do you want this instead? prnt_lst2 = ["0", "¦1", "¦¦2", "¦¦¦3", "¦¦¦¦4", "¦¦¦¦¦5", "¦¦¦¦¦¦6"] print(*prnt_lst2,sep="\n")
21st Apr 2020, 9:05 PM
Choe
Choe - avatar
+ 2
prnt_lst2 = ["0", "¦1", "¦¦2", "¦¦¦3", "¦¦¦¦4", "¦¦¦¦¦5", "¦¦¦¦¦¦6"] print(*prnt_lst2, sep='\n')
21st Apr 2020, 9:05 PM
rodwynnejones
rodwynnejones - avatar
+ 2
Slick , thanks for your reply. So print(*['a', 'b', 'c']) is similar to print('a', 'b', 'c'). Interesting! Thank you so much. Choe & rodwynnejones: Great suggestion! I didn't know that I could use the sep argument when unpacking. This makes things easier. :)
21st Apr 2020, 9:10 PM
Froggy
Froggy - avatar
+ 2
Paste this into your IDE or code playground:- mystring = "sololearnisgreat" print(mystring) print(*mystring)
21st Apr 2020, 9:11 PM
rodwynnejones
rodwynnejones - avatar
+ 2
actually sorry, the unpackaging isnt the issue at all. my bad. print function default parameter for sep is a whitespace. So, you can just do prnt_lst2 = ["0\n", "¦1\n", "¦¦2\n", "¦¦¦3\n", "¦¦¦¦4\n", "¦¦¦¦¦5\n", "¦¦¦¦¦¦6\n"] print(*prnt_lst2,sep="")
21st Apr 2020, 9:14 PM
Choe
Choe - avatar
+ 2
Choe You gave me the right solution the first time. :) I basically wanted to unpack a list of strings and have every string printed on a new line without extra space. The default parameter of sep was indeed the issue, so I needed to replace it with \n.
21st Apr 2020, 9:17 PM
Froggy
Froggy - avatar
+ 1
"\n" brings whatever is next down to the next line. Using a comma in a list will seperate values with a space when you print them. You should call print('0\n' + '|1\n' + '||2\n'......) method 1 works because you used a loop with no "\n" method 2 works because you are effectively taking the "extra space" that would have if you just printed it, and replaces it with "\n" characters
21st Apr 2020, 8:57 PM
Slick
Slick - avatar