【问题标题】:How to add spaces when Concatenating strings连接字符串时如何添加空格
【发布时间】:2020-01-17 15:07:53
【问题描述】:

我试图得到这个输出: 2014-07-26 02:12:18: 德克萨斯州休斯顿

当我尝试使用以下方法完成作业时:

current_time = '2014-07-26 02:12:18:'
my_city = 'Houston'
my_state = 'Texas'
log_entry = current_time + my_city +  my_state
print(log_entry)

我得到这个输出: 2014-07-26 02:12:18:德克萨斯州休斯顿

如何获得 :、休斯顿和德克萨斯州之间的空格

【问题讨论】:

  • 你可以做log_entry = " ".join([current_time, my_city, my_state])
  • 或`log_entry = current_time +" "+ my_city +" "+ my_state
  • 使用字符串格式:f"{current_time} {my_city} {my_state}"

标签: python


【解决方案1】:

在您的连接中将它们作为字符串文字处理:

current_time = '2014-07-26 02:12:18:'
my_city = 'Houston'
my_state = 'Texas'
log_entry = current_time + ' ' + my_city + ' ' + my_state
print(log_entry)

Repl.it

【讨论】:

    【解决方案2】:

    您可以直接添加它们thing + " " + otherthing。或者,如果您知道如何将变量放入列表中,则可以使用上面的 " ".join 方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-26
      • 1970-01-01
      • 1970-01-01
      • 2020-04-19
      • 2014-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多