使用python生成用户名

时间:2016-03-12 23:41:24

标签: python python-3.x

我正在上初级课程而且我对编程非常陌生。我需要知道一个函数,它使用某人姓名的第一个字母,一个人姓氏的前三个字母和一个没有空格的3位数字来生成用户名。 到目前为止,我有这个:

full_name = input("Please enter your name: ")
first_letter = full_name[0]
space_index = full_name.find(" ")
three_letters_surname = full_name[space_index + 1:space_index + 4]
number = random.randrange (1,999)
username = (first_letter, three_letters_surname, number)
print = (username)

我得到的输出是使用John Wayne这样的名字:

"J", "Way", 14

我想知道的是如何更改我的代码,以便得到类似的内容:

jway014

4 个答案:

答案 0 :(得分:5)

您可能最好使用split()将用户名分解为多个部分,然后从那里提取。这将让您检查用户是否输入了至少两个单词的名称,您还可以处理某人输入一个或多个中间名或姓名缩写的情况:

full_name = input("Please enter your name: ").lower().split()
if len(full_name) > 1:
    first_letter = full_name[0][0]
    three_letters_surname = full_name[-1][:3].rjust(3, 'x')
    number = '{:03d}'.format(random.randrange (1,999))
    username = '{}{}{}'.format(first_letter, three_letters_surname, number)
    print(username)
else:
    print('Error. Please enter first name and surname')
    # try again...

如果姓氏长度少于2个字符(并非罕见),则该名称将填充x个字符。

一些例子:

Input            Output
John Wayne       jway014
J J Cool         jcoo777
L Ron Hubbard    lron666
Bob Lo           bxlo001

答案 1 :(得分:2)

试试这个

 import random
 import sys

 names = input("Please enter your name: ").split(" ")
 if not (len(names) > 1):
     print("Please input your full and last name.")
     sys.exit()
 first_letter = names[0][0]
 three_letters_surname = names[-1][:3]
 number = '{:03d}'.format(random.randrange(1, 999))
 username = (first_letter + three_letters_surname + number)
 print(username)

答案 2 :(得分:0)

这个怎么样:

import random

full_name = input("Please enter your name: ")
names = full_name.split(" ")
if (len(names) <= 1):
     print("Please input your full name")
     exit() 
first_letter = names[0][0]
three_letters_surname = names[1][0:3]
number = '{:03d}'.format(random.randrange (1,999))
username = "".join([first_letter, three_letters_surname, str(number)])
print(username)

答案 3 :(得分:0)

替换此行:

username = (first_letter, three_letters_surname, number)

有了这个:

username = '{}{}{:03d}'.format(first_letter.lower(),
                               three_letters_surname.lower(),
                               number)