Hint: You can adjust the default video playback speed in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁This might be due to a temporary outage or because of a configuration issue with your browser. Please see our video player troubleshooting guide to resolve the issue.

String Formatting

In this lesson, you’ll get a quick introduction to formatting strings. Python supports three styles of string formatting:

'Hello %s' % name    # C-style

'My name is {1}, {0} {1}'.format('James', 'Bond')  # Added in Python 3.0

f'I am {age} years old'  # f-string added in Python 3.6

Here are some examples of C-style and newer f-string formatting:

>>>
>>> first = 'James'
>>> last = 'Bond'
>>> age = 90
>>> message = 'No, Mr. %s, I expect you to die' % last
>>> print(message)
No, Mr. Bond, I expect you to die
>>> print('The name is %s, %s %s' % (last, first, last))
The names is Bond, James Bond
>>> print('Sean Connery is now %d years old' % age)
Sean Connery is now 90 years old
>>> print('pi: %f \nshort pi %0.2f' % (math.pi, math.pi))
pi: 3.141593
short pi 3.14
>>> message = f'No, Mr. {last}, I expect you to die'
>>> print(message)
No, Mr. Bond, I expect you to die
>>> print(f'The name is {last}, {first} {last}')
The name is Bond, James Bond
>>> print(f"Sean's age times pi is {age*math.pi}")
Sean's age times pi is 282.7433388230814
>>> print(f"Sean's age times pi is {age*math.pi:.2f}")
Sean's age times pi is 282.74

To learn more, check out the following resources:

Comments & Discussion

Become a Member to join the conversation.