Hi so I wanted to put array elements to become a string. The objective is I wanted to put the string in print function. For instance:
Given an array of [1, 2, 0, 1] Is there any way to make the elements to become one string (i.e. to be 1201)? Lets say the string variable is '''array_elements''' I want to have the output of:
the elements are: 1201.
So of course what I should do to the print function is:
print("the elements are: " str(array_elements), ".")
The problem is, I'm a python beginner and i don't know how to solve the problem without using string function (since this is what google told me to do, but I'm now allowed to use that." What I could think of is by using looping but I still can't manage to make it as one string variable
CodePudding user response:
"".join(str(x) for x in [1, 2, 0, 1])
You need to convert integers to string, since you want to have a string in the end. this is what happens under the hood anyway
However if you actually want an integer this is another task. Then you can do this:
from functools import reduce
reduce(lambda a, b: 10 * a b, [1, 2, 0, 1])
CodePudding user response:
Another option is to print the elements one by one in a loop, using the end=""
argument to avoid ending the line before you're ready:
print("the elements are:", end=" ")
for x in [1, 2, 0, 1]:
print(x, end="")
print()