luka
luka

Reputation: 529

Can only concatenate str not list to str

I want to concatenate a part of a string in list but got Type error

Code

l = [['----Italy', '----Spain', '----France']]

for n in l:
    print("Hi "+n[4:]+" Country")

TypeError: can only concatenate str (not "list") to str

Upvotes: 2

Views: 6736

Answers (4)

AmineBTG
AmineBTG

Reputation: 697

try the below:

_ = ['----Italy', '----Spain', '----France']

for __ in _:
    print("Hi "+ "".join(__[4:]) +" Country")

Output:

Hi Italy Country
Hi Spain Country
Hi France Country

Upvotes: 1

Squishy
Squishy

Reputation: 96

Without changing the list, you can just loop through the sublists too

_ = [['----Italy', '----Spain', '----France']]

for i in _:
    for j in i:
        print("Hi "+__[4:]+" Country")

Upvotes: 0

Cameron Lanata
Cameron Lanata

Reputation: 21

You are iterating over the only element of the list _, which is also a list.

Try this:

_ = ['----Italy', '----Spain', '----France']
for __ in _:
    print("Hi "+__[4:]+" Country")

Upvotes: 1

SuperStew
SuperStew

Reputation: 3054

you made a list of lists at the beginning for some reason

_ = ['----Italy', '----Spain', '----France']

Upvotes: 3

Related Questions