0

I have looked everywhere, and can't find an answer. I am about 1-2 weeks old to Python so not very long. How can I join different items in lists with a string?

In my case, I want to show the 3D dimensions of an object: (Simplified a lot)

my_list = [1, 2, 3]
join_list = my_list[0],"x",my_list[1],"x",my_list[2]
print(join_list)

This returns with:

(1, 'x', 2, 'x', 3)

I am aiming to get 1x2x3 instead of (1, 'x', 2, 'x', 3). Any ideas? Thanks!

4
  • do you want to end up with a string? Commented Oct 26, 2017 at 19:34
  • @RafaelBarros yes Commented Oct 26, 2017 at 19:36
  • 2
    Try this: 'x'.join(map(str, my_list)) Commented Oct 26, 2017 at 19:36
  • the str.join method concatenates everything in the list separating it by itself, in this case, 'x'. it's used with comma sometimes. Important note: you need to have a list of strings, that's why I called the map there, to cast all the numbers to strings. Commented Oct 26, 2017 at 19:38

2 Answers 2

2

This is a simple Python str.join operation. The problem that I just realized was that you have to convert the integers in the list to strings first. You can do that with a simple list comprehension like this.

'x'.join([str(x) for x in my_list])
Sign up to request clarification or add additional context in comments.

4 Comments

Im so dumb thanks :p
How would I do it though if they were other characters such as x/y/z? just wondering
In your follow-up, if x, y, and z are all numbers like above and you just wanted / characters in between, you could do '/'.join([str(x) for x in my_list]). If x, y, and z are strings in my_list, you could just do '/'.join(my_list).
That's great @George_E! Stick with it! :)
0

Try this

'x'.join(str(e) for e in my_list)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.