Python 如何将用户输入转换为列表?
我需要一些帮助,我相信当这个问题得到解决的时候,它会很简单,我没有想到。但这是: 我正在尝试获取以下代码:Python 如何将用户输入转换为列表?,python,python-3.x,Python,Python 3.x,我需要一些帮助,我相信当这个问题得到解决的时候,它会很简单,我没有想到。但这是: 我正在尝试获取以下代码: forename = [input("Forename: ")] forenameFirstLetter = forename[0] email = str(forenameFirstLetter) + "." + surname + "@TreeRoad.net" print ("This is the students email address:" + email) 要打印: J
forename = [input("Forename: ")]
forenameFirstLetter = forename[0]
email = str(forenameFirstLetter) + "." + surname + "@TreeRoad.net"
print ("This is the students email address:" + email)
要打印:
J.Smith@TreeRoad.net
相反,我得到了以下错误:TypeError:无法将'list'对象隐式转换为str
那么,我如何将名字转换成一个列表,这样我就可以打印第一个字母,然后再返回到一个字符串中,这样我就可以将它添加到另一个字符串中?这是因为您试图将字符串转换成一个列表,您只需将字符串本身切片即可 更改此行:
forename = [input("Forename: ")]
到
通过这样做,您将获得字符串的第一个字母。我建议您阅读有关字符串切片的文章,了解更多信息。您做错了什么:
您试图做的是创建一个列表,其唯一元素是字符串。当它是一个列表时,forename[0]
将获取该列表的第一个(也是唯一一个)元素(就像它是直接从input()
中获取一样,只是字符串),而不是从字符串中获取
如何修复它: 无需将其转换为列表,切片表示法允许使用:
forename = input("Forename: ")
forenameFirstLetter = forename[0]
因此,现在不需要在以后转换为字符串:
email = forenameFirstLetter + "." + surname + "@TreeRoad.net"
print ("This is the students email address:" + email)
要更好地理解切片字符串,请执行以下操作: 切片字符串时:
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]
在列表中使用非常相似。您需要的是:
forename = input('Forename: ')
surname = input('Surname: ')
email = forename[0] + "." + surname + "@TreeRoad.net"
print ("This is the students email address:" + email)
您还可以使用更简单的字符串格式:
email = '%s.%s@TreeRoad.net' % (forename[0], surname)
不要在列表中输入字符串作为输入,并对其应用拆分函数,它将被转换为列表。它已被标记为Python 3.x,因此
原始输入不存在。
。。。如果他们使用的是2.x,那么他们的输入将导致一个不同于给定的异常…我的错,没有注意到这是关于Python3的。现在更正。旧样式字符串格式的原因是什么?可以使用email='{0[0]}.{1}'。格式(名字、姓氏)
。。。在打印中,由于它是一个函数,所以只需使用:print('这是学生的电子邮件地址:',email)
(例如:不需要字符串连接)也可以,我个人习惯了“%s”样式。非常感谢
forename = input('Forename: ')
surname = input('Surname: ')
email = forename[0] + "." + surname + "@TreeRoad.net"
print ("This is the students email address:" + email)
email = '%s.%s@TreeRoad.net' % (forename[0], surname)