Mehrshad Mt
Mehrshad Mt

Reputation: 33

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+

Upvotes: 3

Views: 89

Answers (3)

Nikhil Saxena
Nikhil Saxena

Reputation: 36

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) + '+'

Upvotes: 2

ThorSummoner
ThorSummoner

Reputation: 18109

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()

Upvotes: 2

Alex Martelli
Alex Martelli

Reputation: 881675

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.

Upvotes: 2

Related Questions