Printing variables in Python 3.4
Solution 1
Version 3.6+: Use a formatted string literal, f-string for short
print(f"{i}. {key} appears {wordBank[key]} times.")
Solution 2
Try the format syntax:
print ("{0}. {1} appears {2} times.".format(1, 'b', 3.1415))
Outputs:
1. b appears 3.1415 times.
The print function is called just like any other function, with parenthesis around all its arguments.
Solution 3
You can also format the string like so:
>>> print ("{index}. {word} appears {count} times".format(index=1, word='Hello', count=42))
Which outputs
1. Hello appears 42 times.
Because the values are named, their order does not matter. Making the example below output the same as the above example.
>>> print ("{index}. {word} appears {count} times".format(count=42, index=1, word='Hello'))
Formatting string this way allows you to do this.
>>> data = {'count':42, 'index':1, 'word':'Hello'}
>>> print ("{index}. {word} appears {count} times.".format(**data))
1. Hello appears 42 times.
Solution 4
The problem seems to be a mis-placed )
. In your sample you have the %
outside of the print()
, you should move it inside:
Use this:
print("%s. %s appears %s times." % (str(i), key, str(wordBank[key])))
algorhythm
I am a software support engineer for a company that develops and maintains traffic management software.
Updated on August 28, 2020Comments
-
algorhythm almost 4 years
So the syntax seems to have changed from what I learned in Python 2... here is what I have so far
for key in word: i = 1 if i < 6: print ( "%s. %s appears %s times.") % (str(i), key, str(wordBank[key]))
The first value being an int, the second a string, and the final an int.
How can I alter my print statement so that it prints the variables correctly?