2017-10-05 71 views
0

如何形成for循环?python(空闲) - 表单给定名称,如何输入用户名

例如,我想在名称中有两个单词或三个单词时运行for循环。

我需要使for循环为不同数目的名称。 例如,对于两个单词,saint christophersaint得到s并得到christopher得到schristopher的结果。

又如,kyrie andrew irving,我想从andrewirving得到kkyriea得到的kairving结果。

考虑:

saint christopher 
kyrie andrew irving 

结果:

schristopher 
kairving 

我做:

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) 

我应该在哪里解决?

+1

注Stack Overflow是不是免费的代码编写服务。请放下您的代码,以便我们可以专门帮助您编写代码。并阅读https://www.stackoverflow.com/help/how-to-ask以了解如何提出正确的问题。 – SteveFest

+0

你需要阅读关于基本python的教程。 for循环的语法是错误的。您在for循环内的代码并不遥远。 – Steampunkery

回答

0

你试图完成的事情相当简单,即使你的for循环语法关闭,你的问题中的代码也会非常接近它。以下是你需要什么:

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) 

让我带你通过它,一行行:

  1. 先有自己名字的列表
  2. 遍历列表
  3. 斯普利特名列表中,使用空格确定在哪里制作新元素
  4. 指定一个空字符串作为我们的用户名
  5. 迭代所有除了最后一个
  6. 分隔的名字加入他们的第一个字母用户名
  7. 在分隔的名字添加的最后一个项目,以用户名
  8. 打印的用户名

我建议你阅读this。它是官方python文档本身的一个教程。它应该给你一个基本的语法把握,以及如何使用python。

1
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' 

...这将为任意数量的子名称组成一个名称的用户名。它需要每个子名的第一个字母,除了最后一个字母是整个子名。

0

谢谢蒸汽朋克,您的意见帮助了我很多!

我已经编辑我的编码到

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)