What I Learned at Work this Week: Python Basics

String Interpolation

The % sign

'This %s can add strings or %s, like %d.' % ('method', 'numbers', 55)
'This method can add strings or numbers, like 55.'

The .format() method

'This {0} can also add {2} out of {1}.'.format('method', 'order', 'values')
# 'This method can also add values out of order.'
'{0} and {0} and {0} {1}'.format('over', 'again')
# 'over and over and over again'
'My favorite fruit is {favorite}, and my second is {second}.'.format(favorite='bananas',second='blueberries')# 'My favorite fruit is bananas and my second is blueberries'
ourArgument = {'favorite':'bananas','second':'blueberry'}
'I like {favorite} more than {second}.'.format(**ourArgument)
# 'I like bananas more than blueberries.'

f-String

shirtSize='large'
pantSize='32x32'
f'I wear a {shirtSize} shirt and {pantSize} pants.'
# I wear a large shirt and 32x32 pants.
f'The product of 3 and 7 is {3 * 7}.'# ‘The product of 3 and 7 is 21.

Miscellaneous Notes

.split

'This string has spaces.'.split()
// in JS => ['This string has spaces']
# in Python => ['This', 'string', 'has', 'spaces']

String reversal trick

'hello'[1]
// in JS => 'e'
# in Python => 'e'
'hello'[1:4]
// in JS (this doesn’t work)
# in Python => 'ell'
'hello'[:3]
# 'hel'
'hello'[::2]
# 'hlo'
'hello'[::-1]# 'olleh'

Making the effort

Sources

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store