1

When creating a for loop, it appears that python adds spaces.

menuItems = ['apple', 'banana', 'car', 'thing', 'whatever', 'burrito']

menuNum = 1
for menuItem in menuItems:
    print menuNum,'. ',menuItem
    menuNum = menuNum + 1

returns this

1 .  apple
2 .  banana
3 .  car

etc...

Any idea on how I can simply get this without the spacing?

eg.

1. apple
2. banana
3. car
2
  • Your last list still contains spaces, is that how its supposed to be? Commented Feb 12, 2014 at 18:59
  • What does this have to do with a for loop aside from your print statement being inside one? In other words, why do you think this problem is being caused by for? Commented Feb 12, 2014 at 20:37

5 Answers 5

4

Use string formatting. print in Python 2 puts a space for each comma used to separate the items.

>>> data = ['apple', 'banana', 'car', 'thing', 'whatever', 'burrito']
for i, item in enumerate(data, 1):
    print '{}. {}'.format(i, item)
...     
1. apple
2. banana
3. car
4. thing
5. whatever
6. burrito

And use enumerate if you want index as well items.

Sign up to request clarification or add additional context in comments.

Comments

1

Use one of Python's formatting capabilities.

print "{} . {}".format(menuNum, menuItem)  # 2.7+ or 3.x

print "%d . %s" % (menuNum, menuItem)

Comments

0

The print expression in Python 2 puts spaces between the items on a single line. To avoid this, create a single string first that looks like you want to output to appear:

# string formatting
for menuItem in menuItems:
    print '{0}. {1}'.format(menuNum, menuItem)

Or else, use the Python3 print function, which has more options available.

# print function
from __future__ import print_function

for menuItem in menuItems:
    print(menuNum, '. ', menuItem, sep='')

Comments

0

Just use:

from __future__ import print_function
print(menuNum, '. ', menuItem, sep='')

You could also use string formatting:

print '{0}. {1}'.format(menuNum, menuItem)

Comments

0

You have a space after the ". " when using a comma and printing, a space is inserted for you. Altough I use python 3.3, as far as I'm aware, using '+' should still work. Unless I'm missing something; the following would work fine.

print menuNum + '.' + menuItem

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.