How to put a variable in a phrase and print it?


I want to print the sentence; "You have typed (number of characters typed by the user) characters"
I tried this;

original = raw_input(“Enter a word:”)
if len(original)>0:
print original
print len(original) "characters"
print “empty”

Error message is invalid syntax. The problem is in line 4, how should I change it?


you can join strings together with +, which means:

print "hello" + "world"

one of the strings could be a variable of course. However, your variable is an integer, so that won’t work. We could use string formatting:

x = 3
print "%d times" % x

where %d is a placeholder for a decimal value, then after the string we place a percentage sign, this is part of the syntax, it tells python we are now going to provide the variable we promised.

however, a better approach would be format:

x = 3
print "{:d} times".format(x)

.format() is more powerful and flexible.


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.