Python Forum

Full Version: [SOLVED] Print an int with a string
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Is there a way to print an int (score) inside of a string without getting an error?
score = 0
score = score + 1
print("Your score was ")
print(score)
print(" out of 5")
That is the code i currently have, which prints
Output:
Your score was 1 out of 5
And when i change it to this
score = 0
score = score + 1
print("Your score was " + score + " out of 5")
I get the error
Error:
Traceback (most recent call last): File "C:\Users\{USER}\Desktop\Python\game.py", line 115, in <module> print("Congratulations! You scored " + score + " out of 5 points") TypeError: must be str, not int
Is there anyway to fix this? I thought about changing the score to a string in the beginning
score = "0"
But that wouldn't work because when you get a question right, and use
score = score + 1
You would get an error. Unless you use
score = score + "1"
But then score would equal to "01" and not "1"
Please read the docs about strings... specially the format and the f-strings.
As a summary there are 4 methods to create strings with the value of a variable in it:
  1. Using str:
    print("Your score was " + str(score) + " out of 5")
    You have no control of the format used
  2. Using the old % syntax:
    print("Your score was %d out of 5" % score)
    # Or, for more than 1 variable
    print("Your score was %d out of %d" % (score, 5))
    You control the format and is easy for 1 or 2 variables...
  3. The format command:
    print("Your score was {} out of 5".format(score))
    # but can be something complex as:
    print("Your score was {:{w}d} out of {}".format(score, 5, w=3))
    Much versatile than the %-formatting, more complex, also.
  4. f-strings, only for python3.6+
    print(f"Your score was {score} out of 5")
    # Accept almost anything you can do with format
    w = 3
    print(f"Your score was {score:{w}d} out of 5")
    For me the cleanest option to format strings...

There are a few more (strings.Template) but with this 4 options you cover the 99% of the cases.
>>> score = 0
>>> score += 1
>>> print("Your score was {} out of 5".format(score))
Your score was 1 out of 5
>>>