【问题标题】:how to get rid of spaces between variables and strings when printed打印时如何消除变量和字符串之间的空格
【发布时间】:2018-12-22 01:52:31
【问题描述】:
name = 'Alan'
print('My name is', name, '.')

运行这两行时,'Alan' 和句点之间有一个空格。我如何摆脱它们之间的空间?

【问题讨论】:

  • 使用修剪功能
  • 使用格式字符串,例如print(f'My name is {name}.') 或使用 print 函数的可选参数

标签: python string variables


【解决方案1】:

您可以设置sep='',然后明确提及名称前的空格:

print('My name is ', name, '.', sep='')

更好的方法可能是使用字符串格式:

print('My name is {}.'.format(name))

使用 python 3.6+,您可以使用 f-strings 以更简洁的方式做同样的事情:

print(f'My name is {name}.')

最后,最不灵活的选择就是将字符串连接在一起:

print('My name is ' + name + '.')

您甚至可以在设置sep='' 时复制print 在内部所做的事情:

print(''.join(['My name is ', name, '.']))

【讨论】:

    【解决方案2】:

    魔法来了

    name = 'Alan'
    print('my name is '+name+'.')
    

    【讨论】:

      【解决方案3】:

      你可以使用。

      name = 'Alan'
      print('My name is', name + '.')
      

      name = 'Alan'
      print('My name is '+ name + '.')
      

      【讨论】:

      • 现象学上正确,但, 没有添加空格
      • @MadPhysicist 我在打印时提到的原因。我知道如果你在不打印它时这样做,它会形成一个元组。
      • 即使最终结果恰好匹配,您的推理也具有误导性。
      • @MadPhysicist 好的,那么我将删除我的推理。
      【解决方案4】:

      有两种很好的方法可以实现这一点。最好的方法是使用print的可选参数,即sep

      print('My name is', name, '.', sep='')
      

      另一种方法是使用string concatenation。它有点慢,但您可以将这个概念扩展到许多其他领域。连接字符串将它们连接在一起,中间没有空格:

      print('My name is' + name + '.')
      

      【讨论】:

      • 两个版本都会去掉名字前的空格。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-23
      • 2019-10-17
      • 2021-01-01
      • 1970-01-01
      • 2015-04-24
      • 1970-01-01
      相关资源
      最近更新 更多