Home > Blockchain >  How to concatenate items from 2 lists into a string
How to concatenate items from 2 lists into a string

Time:11-02

Trying to concatenate items from 2 lists and output them as a string. However, getting this error - can only concatenate str (not "list") to str

forenames = ['homer','bart','lisa']
surname = ['simpson']

fullnames =[]
for name in forenames:
    fullnames.append(name   ' '   surname)
    

print (fullnames)



 

CodePudding user response:

You can do it in the following way:

forenames = ['homer','bart','lisa']
surname = ['simpson']
for forename in forenames:
print(forename   ' '   surname[0])

The output looks like this:

homer simpson
bart simpson
lisa simpson

CodePudding user response:

You're looking for something like this?

forenames = ['homer','bart','lisa']
surname = ['simpson']

fullnames =[]
for name in forenames:
    fullnames.append(name   ' '   surname[0])
print ("\n".join(fullnames))

Output:

homer simpson
bart simpson
lisa simpson

CodePudding user response:

You can use nested loop to combine the elements:

forenames = ['homer','bart','lisa']
surnames = ['simpson', 'burns']

fullnames = [f"{fname} {sname}" for fname in forenames for sname in surnames]

print(fullnames) # ['homer simpson', 'homer burns', 'bart simpson', 'bart burns', 'lisa simpson', 'lisa burns']

The list comprehension part is equivalent to

fullnames = []
for fname in forenames:
    for sname in surnames:
        fullnames.append(f"{fname} {sname}")

CodePudding user response:

forenames = ['homer','bart','lisa']
surname = ['simpson']

for f in forenames:
    for s in surname:
        fullnames = [f'{f} {s}']
        str_fullnames = ''
        print(str_fullnames.join(fullnames))
  • Related