2016-11-15 55 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