【问题标题】:How to make input() consider an entire string to insert into a list?如何让 input() 考虑将整个字符串插入到列表中?
【发布时间】:2020-05-26 09:07:19
【问题描述】:

你好,我正在学习 python,当我进入列表时,我决定尝试这样的事情:

输入接收用户的全名,打印返回姓氏作为欢迎词。

nome = []
nome = input("Enter your full name ")
print("Welcome Mr. ", nome[2] )

input 将每个字符作为列表的新项插入,因此结果为“I”,因为我输入了“LOIP CANVAS”,而“I”是列表的第 2 位。

细节:

[0] [1] [2] [3]                 
[L] [O] [I] [P]

但我要打印的是列表中的第二个单词而不是第二个字符...

问题是:如何使用input将整个单词添加为列表的新项目?

【问题讨论】:

  • 仅供参考,Python 索引从 0 开始计数的项目,因此 second 项目的索引为 [1]。此外,input() 返回一个字符串(字符序列),而不是它们的列表。
  • 哦我明白了,谢谢@martineau

标签: python list input printing


【解决方案1】:

以下表示解释了您当前在代码中所做的事情:

1. nome = []
2. nome = input("Digite seu nome completo ")
3. print("Seja bem vindo Sr. ", nome[2] )

第 1 步:

第 2 步:

第 3 步:

但是,您可以做的是,您可以将作为输入获得的全名拆分为两个单独的字符串。 Python 提供 split() 方法,将字符串拆分为列表。您可以指定分隔符,默认分隔符是任何空格。一旦你有了名字(primeiro nome)和姓氏(sobrenome)的列表,你就必须访问列表的第二项。你可以参考下面的代码和解释:

1. nome = []
2. nome = input("Digite seu nome completo ")
3. lista_de_nomes = nome.split()
4. sobrenome = lista_de_nomes[1]
5. print("Seja bem vindo Sr. ", sobrenome )

第 1 步:

第 2 步:

第 3 步:

第 4 步:

【讨论】:

  • 这个解释得很好,谢谢!我在想是否可以使用输入中的拆分直接将变量的值设置为插入的第二个名称以恢复更多代码,例如:nome = input.split(1)("Digite seu nome completo ") 你知道这样做的方法吗?跨度>
  • input() 方法从输入中读取一行,转换为字符串并返回。所以,如果你愿意,你可以尝试在 input() 的结果上应用 split() 作为 - input("Enter a string").split() 这将返回一个包含两个字符串的列表。所以,最后你想做的是 - input("Enter a string").split()[1]
  • 完全有效!谢谢.. 当然支持你:) 解决方案:nome = [] nome = input("Digite seu nome completo").split()[1] print("Seja bem vindo Sr.",nome)
【解决方案2】:

使用split:

print("Seja bem vindo Sr. ", nome.split()[1])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-12
    • 2017-06-13
    • 1970-01-01
    • 2021-11-15
    相关资源
    最近更新 更多