Learn Python by Building Data Science Applications
上QQ阅读APP看书,第一时间看更新

Formatting

There are a number of ways to format strings to how you desire.

For example, .rjust and .ljust format the length of the string, adding symbols—if needed—to the right and left, respectively:

>>> ‘hello'.rjust(10, ' ') 
' hello'

>>> ‘hello'.ljust(10, ' ')
'hello '

Similarly, .zfill adds zeros at the beginning of the string:

>>> ‘999'.zfill(10)
'0000000999'

Another important option is to embed values into an existing string using formatting. Indeed, this is very handy as it allows us to embed any type of values without converting them to strings explicitly, and furthermore, defining representation rules and putting them in place. There are a few ways to do that. Let's take a look!