2016-11-15 56 views
1

每当我尝试显示带有第一个初始连接到末尾的名字时,我会得到一个超出字符串索引范围的错误!操纵字符串返回连接的用户名

def ForeName(): 
    return raw_input("Please enter your Forename: ") 

def MiddleName(): 
    return raw_input("please enter your middle name, if none leave blank: ") 

def LastName(): 
    return raw_input("Please enter your last name: ") 


def Test(): 
    ForeNameT = ForeName() 
    MiddleNameT = MiddleName() 
    LastNameT = LastName() 
    if not MiddleNameT: 
     first_username = ForeNameT[0:] + LastNameT[0] 
    elif ForeNameT: 
     first_username = ForeNameT[0:][0] #i want to display the first name with the initial of the first name attached to the end of the first name. 
    else: 
     first_username = ForeNameT[0:] + MiddleNameT[0] 



    return first_username 




print Test() 

回答

0

您可以通过执行def Test(name_method):的参数添加到Test功能,然后设置ifif name_method == 'without_middlename':

试图弄清楚自己你会将print Test()更改为。

+0

我有一个大概的想法,我需要调用你刚刚用于打印测试()行的参数,只是不知道该怎么做!正如我所说,没有寻找答案,只是更简洁的信息,关于我试图做什么。 –

+0

如何将参数传递给函数?试着找出如何做到这一点的谷歌搜索。 – yper

0

我想我知道你正在尝试做的,试着改变你的测试功能:

def Test(): 
    ForeNameT = ForeName() 
    MiddleNameT = MiddleName() 
    LastNameT = LastName() 
    if not MiddleNameT: 
     first_username = ForeNameT + LastNameT 
    else: 
     first_username = ForeNameT + MiddleNameT + LastNameT 

    return first_username 

通知对函数名的更改变量名和返回值,以便打印有什么实际打印

+0

raw_input返回一个简单的字符串,所以你不需要使用[]来索引一个列表或分割一个字符串,[0:]你要求0结束一个字符串的字符,并且[0]只会给出字符串的第一个字符,所以我将T添加到名称中,因为没有它,您会寻址函数的名称而不是新的变量名称 – gkusner