User350178
User350178

Reputation: 59

Concatenating each string in a list to several other strings in Python

I have a loop script that makes a list of strings from a file using the line.split() function, although I want to tag each string with two other strings that form during the loop.

How can I concatenate each string formed from the line.split() function to two other strings?

This is the relevant part of my code

out = str()

for fileName in os.listdir(os.getcwd()):

if line.startswith('Group:'):
    y = line.split()
    t_group = y[]
    group = t_group

if line.startswith("F:"):
   y = line.split()
   #this is where the list of strings is formed

   t_out = group + "    " + ___ # The underscores are a placeholder for each string in the list that I want to add
   out.append(t_out)

Upvotes: 0

Views: 68

Answers (1)

ekneiling
ekneiling

Reputation: 157

If you just want to concatenate all strings in a list, use join:

strs = ["hey", "what's", "up"]
concat = "".join(strs)
print(concat)

# output
heywhat'sup

To append one string at a time, you could do something like:

output_string = "prepended text"
for string in strs:
    output_string += string
    print(output_string)

printed output would be:

prepended text
prepended texthey
prepended textheywhat's
prepended textheywhat'sup

Of course, you could add a space into the string each time you append your string from the list too.

output_string += f" {string}"

which would print:

prepended text
prepended text hey
prepended text hey what's
prepended text hey what's up

Upvotes: 1

Related Questions