【问题标题】:How to remove space in python 2.7.5如何在 python 2.7.5 中删除空格
【发布时间】:2014-07-30 07:13:00
【问题描述】:

当我在 python 2.7.5 中使用代码时

for i in [1,2]:
       print 'distance',':400@CA',':',i,'@CA'

我得到了以下

distance :400@CA : 1 @CA

distance :400@CA : 2 @CA

我想删除空格(例如,在 :,1,@CA 之间),这样输出就会像

distance :400@CA :1@CA

distance :400@CA :2@CA

我也尝试使用 sep='' 或 end='' 但它们仍然不起作用。任何建议将不胜感激。

【问题讨论】:

    标签: python string formatting


    【解决方案1】:

    我会使用string formatting operator %

    for i in [1,2]:
       print 'distance :400@CA :%d@CA' % i
    

    这使您可以很好地控制事物的布局方式。

    【讨论】:

      【解决方案2】:

      您可以使用 %d 运算符:

      for i in [1,2]:
             print 'distance',':400@CA',':','%d@CA' % i
      

      或者你可以使用join:

      for i in [1,2]:
                 print 'distance'+':400@CA:'.join(i,'@CA')
      

      参考:How to print a string of variables without spaces in Python (minimal coding!)

      希望这会有所帮助...

      【讨论】:

        【解决方案3】:
          for i in [1,2]:
                   print 'distance',':400@CA',':'+str(i)+'@CA'
        
        Output: distance :400@CA :1@CA
                distance :400@CA :2@CA
        

        使用 ,(逗号)将在打印时增加空格。使用 + 更好地连接

        【讨论】:

          【解决方案4】:

          在打印中使用 sep 标签

          from __future__ import print_function
          print('distance',':400@CA',':',i,'@CA', sep = '')
          

          【讨论】:

            猜你喜欢
            • 2018-02-21
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2010-10-31
            • 1970-01-01
            • 2013-10-10
            • 2021-07-29
            • 2011-05-15
            相关资源
            最近更新 更多