简体   繁体   中英

removing space from string in python

def digits_plus(test):

   test=0
   while (test<=3):

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


   return()

digits_plus(3)

The output is: 0+ 1+ 2+ 3+

However i would like to get: 0+1+2+3+

If you're stuck using Python 2.7, start your module with

from __future__ import print_function

Then instead of

print str(test)+"+",

use

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

You'll probably want to add a print() at the end (out of the loop!-) to get a new-line after you're done printing the rest.

Another method to do that would be to create a list of the numbers and then join them.

mylist = []

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

we get the list [1, 2, 3]

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

You could also use the sys.stdout object to write output (to stdout) that you have more fine control over. This should let you output exactly and only the characters you tell it to (whereas print will do some automatic line endings and casting for you)

#!/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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM