【问题标题】:Python: Removing a space before a string [duplicate]Python:删除字符串前的空格[重复]
【发布时间】:2021-02-21 18:33:10
【问题描述】:

print ("The number is", (roll),'.')

数字是 5。

我想删除 '5' 和 '.' 之间的空格

我尝试了几种不同的方法来删除句点前的空格,但我得到了错误或相同的结果。

【问题讨论】:

  • 试试这个:roll + ‘.’
  • 对于像我一样对此感到惊讶的其他人:打印函数中多个参数的默认分隔符是空格,因此它在每个元素之间添加空格。您可以使用 print(... , sep="") 覆盖它

标签: python


【解决方案1】:

您需要一个字符串格式化方法或连接方法。以下将给您相同的结果


print (f"The number is, {roll}.")
print ("The number is, {}.".format(roll))
print ("The number is"+' '+ str(roll) +'.')
print ("The number is %s. "%(a))

【讨论】:

  • print('The number is {}.'.format(roll)),如果您使用较旧的 Python 版本。
  • 非常感谢您。为什么这行得通?我要打印的字符串前f的作用是什么?
【解决方案2】:

您的问题有多种解决方案。我可以推荐 f-strings

print ("The number is", (roll),'.')

变成

print(f"The number is {roll}.")

【讨论】:

    【解决方案3】:

    您的问题有多种解决方案,其中一种解决方案可以使用 .format 函数完成。

    print ("The number is {}.".format(roll))

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-12-12
      • 2013-02-06
      • 1970-01-01
      • 1970-01-01
      • 2016-04-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多