【问题标题】:Python integer concatenationPython整数连接
【发布时间】:2019-01-22 08:34:43
【问题描述】:

如何使用正斜杠(/)连接整数和字符串,如下所示

i am trying to get such output 
x=1
y=2
c=3
output without space 1/2/3

# Also in case if

x=1
b=2
c="a"

output : 1/2/a   

【问题讨论】:

  • 你在为哪一部分苦苦挣扎?
  • 输出应该是什么?如果是一个字符串,例如仅用于打印:output=str(x)+str(y)+str(c)
  • 你应该展示你尝试过的东西。
  • 感谢@JonnyTischbein 成功了
  • @Goe 是正斜杠,不是反斜杠

标签: python string integer concatenation


【解决方案1】:

您可以使用.format()

a = 1
b = 2
c = 3

out = "{}/{}/{}".format(a,b,c)
print(out)

对于反斜杠 \ 使用:

out = "{}\\{}\\{}".format(a,b,c)

因为反斜杠需要转义

【讨论】:

  • OP 想要正斜杠,而不是反斜杠
  • 看输出,它包含正斜杠,而不是反斜杠
【解决方案2】:

在 Python 中有很多方法可以实现你的目标,以下是我常用的一些:

x=1
y=2
z=3

output1 = '%s/%s/%s' % (x, y, z)
output2 = '{}/{}/{}'.format(x, y, z) 

因为可读性,我认为最好的是这个:

output3 = '{a}/{b}/{c}'.format(a=x, b=y, c=c) 

欲了解更多信息,请查看 https://docs.python-guide.org/writing/structure/

【讨论】:

    【解决方案3】:

    如果您使用的是 Python 3,则可以使用 sep 关键字参数使 print 具有此行为

    print(1, 2, "a", sep="/")
    # 1/2/a
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-16
      • 1970-01-01
      • 2016-09-28
      • 2012-07-18
      • 2011-02-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多