Reputation: 17
How to form a for loop?
For example, I want to run a for loop when there is a two words or three words in a name.
I need to make for
loop for different number of names.
For example, for two words, saint christopher
to get just the s
from saint
and get christopher
to get the result of schristopher
.
Another example, kyrie andrew irving
, I want to get k
from kyrie
, a
from andrew
and irving
to get the result of kairving
.
Given:
saint christopher
kyrie andrew irving
Result:
schristopher
kairving
I have done:
s = ("saint christopher", "kyrie andrew irving")
for s >= 2:
first = s.split()
separate = list(first[0])
secondword = first[1]
firstletter = separate[0]
print(firstletter+secondword)
Where should I fix?
Upvotes: 0
Views: 125
Reputation: 17
Thank you Steampunkery, your comments helped me alot!
I have edited my coding to
for line in infile:
first = line.lower().split()
username=""
for i in first[0:-1]:
username+=i[0]
newusername+= first[-1]
lastname = newusername[:9]
print(lastname)
Upvotes: 0
Reputation: 3874
What you are trying to accomplish is fairly simple, and you get pretty close to it in the code in your question, even though your for loop syntax is off. Here is what you need:
names = ['kyrie andrew irving', 'saint christopher']
for item in names:
name_sep = item.split(' ')
username = ""
for i in name_sep[0:-1]:
username += i[0]
username += name_sep[-1]
print(username)
Let me walk you through it, Line by Line:
I recommend you read this. It is a tutorial from the official python docs themselves. It should give you a basic grasp of syntax and how to use python in general.
Upvotes: 0
Reputation: 3698
def make_username(name):
return ''.join(x[0].lower() if i != len(name.split()) - 1 else x.lower() for i, x in enumerate(name.split()))
>>> make_username('saint christopher')
'schristopher'
>>> make_username('kyrie andrew irving')
'kairving'
>>> make_username('holly mother of god')
'hmogod'
...this will make a username for a name consisting of arbitrary amount of subnames. It takes first letter of every subname, except the last one where it takes the whole subname.
Upvotes: 1