Reputation: 39
Having some issues trying to solve this. The goal is to insert a value n in every other letter in the provided string a.
def insert(a,n):
k = n
P = 1
res = list(''.join(i + k * (P%1==0)
for P, i in enumerate(a)))
return str(res)
insert('My name is Pamela', 'x')
the return that I'm getting looks like this
['M', 'x', 'y', 'x', ' ', 'x', 'n', 'x', 'a', 'x', 'm', 'x', 'e', 'x', ' ', 'x', 'i', 'x', 's', 'x', ' ', 'x', 'P', 'x', 'a', 'x', 'm', 'x', 'e', 'x', 'l', 'x', 'a', 'x']
How can I make this come as one string instead of different strings?
Upvotes: 0
Views: 567
Reputation: 803
If you wanted to insert 'x'
between each 2 letters in a
, but not at the very end, then this is what you want to write :
def insert(a, n):
return n.join(a)
print(insert('My name is Pamela', 'x'))
#Mxyx xnxaxmxex xixsx xPxaxmxexlxa
Upvotes: 0
Reputation: 58
Try:
fin = ""
return fin.join(res)
This should combine the string.
Returns:
Mxyx xnxaxmxex xixsx xPxaxmxexlxax
Upvotes: 0
Reputation: 21275
Here's a simpler way solution:
def insert(a, n):
res = ''.join(x + y for x, y in zip(a, n * len(a)))
return res
print(insert('My name is Pamela', 'x'))
Result:
Mxyx xnxaxmxex xixsx xPxaxmxexlxax
n * len(a)
creates the string nnnn...
with the same length as a
& zip
turns the two strings into pairs of one character from each string. Then join
turns that into a string.
Upvotes: 0
Reputation: 22776
You can simply use ''.join
:
def insert(a, n):
return ''.join(l + n for l in a)
print(insert('My name is Pamela', 'x'))
Output:
Mxyx xnxaxmxex xixsx xPxaxmxexlxax
Upvotes: 2