2017-03-04 101 views
2

我需要一些帮助,我敢肯定,当这个答案是非常简单的,我没有想到。但在这里,它是:如何将user_input转换为列表?

我试图让这个代码:

forename = [input("Forename: ")] 
forenameFirstLetter = forename[0] 

email = str(forenameFirstLetter) + "." + surname + "@TreeRoad.net" 
print ("This is the students email address:" + email) 

打印:

[email protected] 

相反,我得到这个错误:TypeError: Can't convert 'list' object to str implicitly

所以如何我是否会将姓氏放入列表中,以便我可以打印第一个字母,然后返回到字符串中,以便将其添加到其他字符串中?

回答

4

你做了什么错:

你在哪里试图做的是创造什么,其唯一的元素是一个字符串列表。当它是一个列表时,forename[0]将采用该列表中的第一个(也是唯一)元素(就像该字符串是从input()直接获取的那样),但不是来自该字符串。


如何解决此问题:

没有必要将它转化成列表,切片标志允许使用:

forename = input("Forename: ") 
forenameFirstLetter = forename[0] 

所以,现在是不必要后来转换为字符串:

email = forenameFirstLetter + "." + surname + "@TreeRoad.net" 
print ("This is the students email address:" + email) 

到u nderstand更好的切片字符串:

0 | 1 | 2 | 3 | (index) 
f | o | o | . | (string) 

当你切的字符串:

s = "foo." 

s[0] #is "f" because it corresponds with the index 0 
s[1] #is "o" 
s[2] #is "o" 
s[0:2] #takes the substring from the index 0 to 2. In this example: "foo" 
s[:1] #From the start of the string until reaching the index 1. "fo" 
s[2:] #From 2 to the end, "o." 
s[::2] #This is the step, here we are taking a substring with even index. 
s[1:2:3] #You can put all three together 

所以语法string[start:end:step]

用于列表非常相似。

+1

非常感谢你 –

0

你需要的是:

forename = input('Forename: ') 
surname = input('Surname: ') 

email = forename[0] + "." + surname + "@TreeRoad.net" 
print ("This is the students email address:" + email) 

您还可以使用更简单的读取字符串格式化:

email = '%s.%[email protected]' % (forename[0], surname) 
+1

它已被标记为Python 3.x,所以'raw_input'不存在......并且如果它们使用2.x,那么它们的'输入'会导致与其它异常不同的异常给... –

+0

我的不好,没有注意到它是关于Python3的。现在更正。 –

+0

旧式字符串格式化的任何原因?可以使用'email ='{0 [0]}。{1}'。format(forename,surname)'...在打印中,因为它是一个函数,只需使用:'print('This is the students email地址:',email)'(例如:不需要字符串连接) –

-1

不要采取列表采取字符串作为输入内输入和应用分割功能它将被转换成列表。

+0

请详细说明或不吸引upvotes。 – Gang