【问题标题】:Can someone please tell me why the two python codes below produce entirely different outcomes?有人可以告诉我为什么下面的两个 python 代码会产生完全不同的结果吗?
【发布时间】:2017-08-08 18:53:43
【问题描述】:

这是我的代码:

>>> hellos = [ "hello", "bonjour", "hola"]                                                                     
>>> for hi in hellos:                                                                                          
...     print(hi + " World!")                                                                                  
...                                                                                                            
hello World!                                                                                                   
bonjour World!                                                                                                 
hola World! 


>>> hellos = [ "hello", "bonjour", "hola"]                                                                     
>>> for hi in hellos:                                                                                          
...     print("hi" + " World!")                                                                                
...                                                                                                            
hi World!                                                                                                      
hi World!                                                                                                      
hi World!

【问题讨论】:

  • 请修正格式
  • 你期望输出是什么?
  • 因为当你在 "..." 中包含一些东西时,它是一个字符串
  • nedbatchelder.com/text/names.html - 可能是一个好的开始

标签: python python-3.x syntax


【解决方案1】:

第二次,hi 用引号引起来。所以它是一个字符串文字。它不是一个变量。具体来说,它不是迭代器的值。

【讨论】:

    【解决方案2】:

    首先,您将 hellos i.e hi 的值添加到 " World!"

    print(hi + " World!")  
    

    所以,输出是:

    hello World!
    bonjour World!
    hola World!
    

    其次,您只需将"hi"" World!" 连接起来。

    print("hi" + " World!") 
    

    所以,输出是:

    hi World!
    hi World!
    hi World!
    

    【讨论】:

      【解决方案3】:

      你只是在第二个中连接字符串

      “嗨”+“世界!” = 嗨,世界!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-06-17
        • 2019-12-02
        • 1970-01-01
        • 1970-01-01
        • 2018-04-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多