1

I am trying this, where i is an integer:

sys.stdout.write('\thello world %d.\n' % i+1)

and it says "cannot concatenate str and int". I have tried various combinations:

int(i) + 1
i + int(1)

... but it's not working

0

3 Answers 3

6
sys.stdout.write('\thello world %d.\n' % (i+1))

Mind the brackets.

(The % operator binds more tightly than the + operator, so you wind up trying to add 1 to the formatted string, which is an error.)

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

Comments

2

How about:

sys.stdout.write('\thello world %d.\n' % (i+1))

Python interpret your way as ('...' % i) + 1

Comments

1

str.format is preferred if your Python version is new enough to support it (Python2.6+) see that you don't even need to worry about the precedence of % and + here.

sys.stdout.write('\thello world {}.\n'.format(i+1))

or as the title of the question suggests - using a print statement

print '\thello world {}.'.format(i+1)

In Python3, print is a function, so you need to call it like this

print('\thello world {}.'.format(i+1))

† In Python2.6 you need to use {0} in stead of plain {}

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.