0

How can you concatenate strings and numbers in python

vec1=["a","b","c"]
vec2=[1,2,3]

What I want is to combine the two vectors such that the following is the output:

vec3=["a1","b2","c3"]

2 Answers 2

1

You can use a combination of zip and list comprehensions.

zip takes a list of iterables, and binds together every n-th element of each iterable into a new list. Here's how zip would handle vec1 and vec2:

>>> zip(vec1, vec2)
[('a', 1), ('b', 2), ('c', 3)]

So now you have a list of tuples, each containing a matched pair from both vec1 and vec2; all you need to do next is process your elements in order, and combine them into a single string. This can be concisely achieved with a list comprehension:

vec3 = [a+str(b) for a, b in zip(vec1, vec2)]
Sign up to request clarification or add additional context in comments.

Comments

1
['{}{}'.format(*x) for x in zip(vec1, vec2)]

Comments

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.