Felipe
Felipe

Reputation: 11

How do I store the results of each iteration of a for loop inside a variable

I wrote the following code:

full_name = "John Francis Bean Coppola"
full_name_as_list = full_name.lower().split()

for name in (full_name_as_list):
a = name[0]
print(a)

When I run print(a) It returns:

j
f
b
c

I wanna define a variable like joined_results = something such that if I run print(joined_results) it returns:

jfbc

The purpose of the code I'm trying to write is to extract the initials of a name to create an e-mail address. For example: John Francis Ford Coppola = [email protected]

Upvotes: 1

Views: 351

Answers (2)

will-hedges
will-hedges

Reputation: 1284

You can use join to join together all the items in a list.

print("".join([name[0] for name in full_name_as_list]))

Here, I'm joining the items together with a blank string, but for other applications, you can join them with anything, like so:

print("&".join([name[0] for name in full_name_as_list]))

would print

j&f&b&c

Upvotes: 0

Tytrox
Tytrox

Reputation: 538

full_name = "John Francis Bean Coppola"
full_name_as_list = full_name.lower().split()

initials = []
for name in (full_name_as_list):
    initials.append(name[0])

#edit
print(''.join(initials))

Upvotes: 1

Related Questions