jessica
jessica

Reputation: 1355

Concatenating Strings and Numbers in Python

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"]

Upvotes: 0

Views: 232

Answers (2)

xbug
xbug

Reputation: 1472

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

Upvotes: 1

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798576

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

Upvotes: 1

Related Questions