Programming & Scripting Tutorials

Python: Formatting Strings

It's very important that you know how to format strings, in this lesson we will learn how to.

Firstly let's make the user input their name and age:

name = raw_input("What's your name?")
age = input("How old are you?")

Now we have these two, we should store them in a tuple:

TupleOne = (name, age)


Ok, so now we have the users name and age in a tuple..

What if we wanted to output their name and age in a string (for example "Hi Joe, How's it going at 99?")?
Well what we would do is we would format a string so that we can insert the variables into it.
The way to do this is to the the % sign, followed by a letter for the type of variable you want to replace it with (for example %s is for strings and %i is for integers):

String = "Hi %s, How's it going at %i?


So now we have a string with some holes in it.. The way to fill these holes is to combine the string and the tuple:

StringForPrint = String % TupleOne

In the above the % sign just means the string with holes in is "String", fill the holes using "TupleOne".

We can then "print(PrintString)" to see the results.

This Python tutorial was written by


Back to Python

Advertisement: