[英]How to convert a user_input into a list?
I need some help this and I'm sure when this is answered it will be pretty simple that I didn't think of. 我需要一些帮助,并且我敢肯定,一旦回答了这个问题,那将是我从未想到的非常简单的事情。 But here it is:
但是这里是:
I'm trying to get this code: 我正在尝试获取以下代码:
forename = [input("Forename: ")]
forenameFirstLetter = forename[0]
email = str(forenameFirstLetter) + "." + surname + "@TreeRoad.net"
print ("This is the students email address:" + email)
to print: 打印:
J.Smith@TreeRoad.net
Instead I'm getting this error: TypeError: Can't convert 'list' object to str implicitly
相反,我收到此错误:
TypeError: Can't convert 'list' object to str implicitly
so how would I go about forename into a list so I can print the first letter and then back into a string so i can add it to other string? 所以我将如何将姓氏放入列表中,这样我可以打印第一个字母,然后再返回一个字符串,以便可以将其添加到其他字符串中?
What you where trying to do was creating a list whose only element was a string. 您想要做的是创建一个列表,该列表的唯一元素是字符串。 When it is a list,
forename[0]
will take the first (and only) element of that list (Just the string as if it was taken directly from input()
), but not from the string. 当它是一个列表时,
forename[0]
将采用该列表的第一个(也是唯一的)元素(就像字符串一样,就好像它直接来自input()
),而不是字符串。
It is not necessary to convert it to list, slice notation allows to use: 不必将其转换为列表,切片符号允许使用:
forename = input("Forename: ")
forenameFirstLetter = forename[0]
So, now it's unnecessary to convert to string later: 因此,现在无需稍后再转换为字符串:
email = forenameFirstLetter + "." + surname + "@TreeRoad.net"
print ("This is the students email address:" + email)
0 | 1 | 2 | 3 | (index)
f | o | o | . | (string)
When you slice a 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
So the syntax is string[start:end:step]
. 因此语法为
string[start:end:step]
。
For use in lists is very similar. 在列表中使用非常相似。
That is because you are trying to convert the string to a list you can just slice the string itself. 那是因为您试图将字符串转换为列表,所以您只能对字符串本身进行切片。
Change this line: 更改此行:
forename = [input("Forename: ")]
to 至
forename = input("Forename: ")
By doing this you are getting the first letter of the string. 这样,您将获得字符串的第一个字母。 I would recommend reading this article on string slicing to learn more about it.
我建议阅读本文章字符切片更多地了解它。
What you need is: 您需要的是:
forename = input('Forename: ')
surname = input('Surname: ')
email = forename[0] + "." + surname + "@TreeRoad.net"
print ("This is the students email address:" + email)
You can also use simpler to read string formatting: 您还可以使用更简单的方法来读取字符串格式:
email = '%s.%s@TreeRoad.net' % (forename[0], surname)
不要在列表中输入内容,而是将字符串作为输入并对其应用拆分功能,它将转换为列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.