【问题标题】:Python print statement adds spaces between argumentsPython print 语句在参数之间添加空格
【发布时间】:2021-10-28 16:16:05
【问题描述】:

我正在编写一个非常基本的 hello 程序,但在名称和第一个感叹号之间不断出现一个空格,我在代码中没有看到。我尝试用几种不同的方式重新格式化字符串部分来连接间距,但我无法弄清楚是什么导致了额外的空间。我试过单独做感叹号,或者下一句的第一部分,但它总是有额外的空间 在变量'name' 之后。

相比之下,可变年龄后的感叹号没有多余的空间,这是我希望他们两个看起来的样子。

这是代码和屏幕截图 - 提前感谢您。

name = input('Please enter your name: ')
age = input('Please enter your age: ')

print("Hello",name,"! You are",age,"nice to meet you!")

【问题讨论】:

    标签: python spacing


    【解决方案1】:

    python 打印函数会自动在参数之间添加一个空格。您应该将字符串连接(连接)在一起,然后打印它们

    print("a","b") # a b
    print("a" + "b") # ab
    

    在 python 中,您可以使用“f-strings”,这是一种“模板化”字符串的方法。 {} 中的文本被视为 python,因此您可以在其中放置变量。

    print(f"Hello {name}! You are {age} nice to meet you!")
    

    f-strings 是 python 中最好的方法,但是第一个带有“+”的解决方案可以很好地用于这个用例

    【讨论】:

    • + 运算符是连接字符串最慢的
    • 我同意,但是我建议这种方法的原因是因为 OP 是 python 的初学者,我想尝试展示我所说的适用于几乎所有语言的“基本”技术. F 字符串仅是 python,因此如果 OP 想要使用不同的语言,它们将无法工作。我将更新以显示 f-strings asweel
    • 谢谢,效果很好!我也用整数尝试过,但收到错误,你有没有用整数删除空格的建议?再次感谢。
    • 对于整数(以及所有非字符串),您需要先将 int 转换为字符串。使用str(Varname) 来做到这一点
    【解决方案2】:

    您可以使用f-strings。那更好,更pythonic:

    print(f"Hello {name}! You are {age}. Nice to meet you!")
    

    ,在python中默认添加了一个空格。

    【讨论】:

      【解决方案3】:

      你也可以像这样使用.format

      name = input('Please enter your name: ')
      age = input('Please enter your age: ')
      
      print("Hello {}! You are {} nice to meet you!".format(name , age))
      

      或:

      name = input('Please enter your name: ')
      age = input('Please enter your age: ')
      
      print("Hello {0}! You are {1} nice to meet you!".format(name , age))
      

      第二种解决方案在这种情况下会很有用:

      print("{0} is software engineer. also his son want to be programmer. {0} is good trainer".format("jackob"))
      

      它是如何工作的?
      .format(...) 中的每一件事都有一个索引!例如,在.format("jackob" , "sara"),“jackob”索引为0,“sara”索引为1

      【讨论】:

        【解决方案4】:

        使用带有 C 样式标志的 print() 语句。它使您可以精确控制字符串的输出方式。

        print('Hello %s! You are %d. Nice to meet you!' % (name, age))
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-05-14
          • 2021-03-22
          • 1970-01-01
          • 2020-01-18
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多