How do I print a list that has numbers and strings to a single string?
For example, I have this list: ["(",3,"+",4,"-",3,")"], I would like it to be printed as :(3+4-4). I tried to use the join command, but I keep having issues with the numbers.
-
What was the issue with the numbers? Isn't that what the question is about? Pretty sure there will be a duplicate question.Open AI - Opting Out– Open AI - Opting Out2015-03-24 22:42:47 +00:00Commented Mar 24, 2015 at 22:42
Add a comment
|
1 Answer
You have to cast the ints to str, str.join expects strings:
l = ["(",3,"+",4,"-",3,")"]
print("".join(map(str,l)))
(3+4-3)
Which is equivalent to:
print("".join([str(x) for x in l]))
To delimit each element with a space use:
print(" ".join(map(str,l)))
3 Comments
Twhite1195
that actually did the trick, but, is there a way to have it create a space between each list element? I'm doing a RPN calculator, and when I return the results I must show 3 4 + 3 -
Twhite1195
oooh I see, that makes a lot of sense xD, I've been trying it for hours, you really saved my life
Padraic Cunningham
No worries, glad it helped and that I could save your life with code ;)