user13024918
user13024918

Reputation:

How do I append same string variable to a string in a loop

I have a list, temp1 = ['a','b','c','d','e','f']

I want the output as a new list new_list=['a.b.c.d.e.f']

I had tried this

def combine(temp1, lstart, lend):
    global y,z,x
    for w in temp1[lstart:lend-1]: 
        y=w+"."
        z=w
    for w in temp1[lend-1:lend]:
        z=w

for i in edge_names:
    temp1=(i.split('.'))
    print(temp1)
    right = len(temp1) - 2
    combine(temp1, 0, right)

but unable to get the desired result. Please help!

Upvotes: 1

Views: 65

Answers (2)

user2736738
user2736738

Reputation: 30916

You can also do this (but there are even better ways as pointed in other answers).

s=''  
for i in range(len(temp1)-1):
    s =  s + temp1[i] + '.'
if len(temp1) > 0:
    s =  s + temp1[-1]
newlist = [s]

Upvotes: 0

WangGang
WangGang

Reputation: 533

A simple solution would be to use the .join method

new_list = [".".join(temp1)]

This will give you the desired output of new_list = ["a.b.c.d.e.f"]

Upvotes: 4

Related Questions