0

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

1
  • you don't have to use str function, just print(...) or use f-strings. If you want to join list elements, use ''.join(your_list) and make sure the list contains strings. Commented Oct 20, 2022 at 3:00

2 Answers 2

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

Comments

0

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

1 Comment

oh my god, why did I not think of this. This will work so well with the looping method of my own. Thank you so much

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.