【问题标题】:removing space from string in python从python中的字符串中删除空格
【发布时间】:2015-04-21 17:28:52
【问题描述】:
def digits_plus(test):

   test=0
   while (test<=3):

       print str(test)+"+",
       test = test+1


   return()

digits_plus(3)

输出是: 0+ 1+ 2+ 3+

但是我想得到:0+1+2+3+

【问题讨论】:

    标签: python string space


    【解决方案1】:

    另一种方法是创建一个数字列表,然后加入它们。

    mylist = []
    
    for num in range (1, 4):
        mylist.append(str(num))
    

    我们得到列表 [1, 2, 3]

    print '+'.join(mylist) + '+'
    

    【讨论】:

      【解决方案2】:

      如果您在使用 Python 2.7 时遇到问题,请使用以下命令启动您的模块

      from __future__ import print_function
      

      然后代替

      print str(test)+"+",
      

      使用

      print(str(test)+"+", end='')
      

      您可能需要在末尾添加 print()(在循环之外!-),以便在打印完其余部分后换行。

      【讨论】:

        【解决方案3】:

        您还可以使用sys.stdout 对象将输出(到标准输出)写入您可以更好地控制的输出。这应该可以让你准确地输出你告诉它的字符(而 print 会为你做一些自动换行和强制转换)

        #!/usr/bin/env python
        import sys
        
        test = '0'
        
        sys.stdout.write(str(test)+"+")
        
        # Or my preferred string formatting method:
        # (The '%s' implies a cast to string)
        sys.stdout.write("%s+" % test)
        
        # You probably don't need to explicitly do this, 
        # If you get unexpected (missing) output, you can 
        # explicitly send the output like
        sys.stdout.flush()
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-09-25
          • 2017-11-20
          • 2014-01-26
          • 2011-09-21
          相关资源
          最近更新 更多