【问题标题】:Possibility to have no spaces when creating a string? [duplicate]创建字符串时可能没有空格吗? [复制]
【发布时间】:2018-04-06 08:32:53
【问题描述】:

例如,如果我这样做:

for i in '12345':
        print("Welcome",i,"times")

它输出:

Welcome 1 times
Welcome 2 times
Welcome 3 times
Welcome 4 times
Welcome 5 times

但我想要这样:

Welcome1times
Welcome2times
Welcome3times
Welcome4times
Welcome5times

这可能吗?

【问题讨论】:

  • print("Welcome" + i + "times")
  • print("welcome{}times".format(i))

标签: python python-3.x loops for-loop iteration


【解决方案1】:

可以,通过使用print functionsep 参数:

for i in '12345':
    print("Welcome", i, "times", sep="")

>>>
Welcome1times
Welcome2times
Welcome3times
Welcome4times
Welcome5times

顺便说一句,您应该考虑使用标准字符串格式化方法生成字符串。 例如,你可以这样做:

for i in '12345':
    print("Welcome%stimes"%i)

或者以更 Python-3 的方式:

for i in '12345':
    print("Welcome{i}times".format(i=i))

甚至更短(感谢@StefanPochmann)

for i in '12345':
    print(f"Welcome{i}times")

【讨论】:

  • print(f'Welcome{i}times')
  • 谢谢,我忘了选择你的答案!
猜你喜欢
  • 1970-01-01
  • 2018-11-25
  • 1970-01-01
  • 1970-01-01
  • 2020-08-30
  • 1970-01-01
  • 2021-09-12
  • 2023-03-04
  • 1970-01-01
相关资源
最近更新 更多