Python text formatting

Convert a variable to a string

Repr(x) => this function gives a representation of the object in string. In string variables for example, the repr() functions adds backlashes and quotes.

repr('Hello, world.')
"'Hello, world.'"

Str(x) => this function will convert the value to a string, it may have a similar result to repr(), but not all the time.

str('Hello, world.')
'Hello, world.'

The format method of a string object

The format method allows inserting values in a specific template string:

'Hello world and you {0}'.format("Matthieu")
#'Hello world and you Matthieu'

You can apply specific number formats

'The screen width is {0:.0f} pixels'.format(1801.568)
#'The screen width is 1802 pixels'
'The screen width is {0:.2f} pixels'.format(1801.568)
#'The screen width is 1801.57 pixels'
print('Hello {first} and also hello {second} and finally hello {third}.'.format(first='world', second="me", third="you"))
#Hello world and also hello me and finally hello you.

You can also use the unpacking shortcuts for lists and dictionaries:

Dico = {'first':"someone", 'second':"someone else", 'third':"me of course"}
print('Hello {0[first]} and also hello {0[second]} and finally hello {0[third]}.'.format(Dico))
print('Hello {first} and also hello {second} and finally hello {third}.'.format(**Dico))
#Hello someone and also hello someone else and finally hello me of course.
 
TheList = ["someone", "someone else", "me of course"]
print('Hello {0} and also hello {1} and finally hello {2}.'.format(*TheList))
#Hello someone and also hello someone else and finally hello me of course.
Matthieu Liatard
Remember this!
Remember this
Play!
Take a quizz on this subject
Close

Hello :)
At Question-Player, we want to share more knowledge and help you never forget anything ever. And for free.

To show us your support, you can create an account:

Login / Create an account
Rate this article :
1
2
3
4
5

Up next

Related posts