Use the power of rf''
- a r
aw f
-string:
>>> from getpass import getuser
>>> rf"c:\Users\{getuser()}\Documents\_EssentialWindowsData"
'c:\\Users\\rnag\\Documents\\_EssentialWindowsData'
The Power of Raw (Strings)
Assume we have a string embedded with \n
newline and \t
tab characters:
>>> print('\my\name\is\tom\nhanks')
\my
ame\is om
hanks
>>> print(r'\my\name\is\tom\nhanks')
\my\name\is\tom\nhanks
The Power of F (Strings)
f-strings allow interpolation of variables directly in strings. They are very fast, even (slightly) better than plain string concatenation (+
).
>>> first = 'Jon'
>>> last = 'Doe'
>>> age = 23
>>> 'my name is {first} {last}, and I am {age}'
'my name is {first} {last}, and I am {age}'
>>> f'my name is {first} {last}, and I am {age}'
'my name is Jon Doe, and I am 23'
>>> 'my name is ' + first + ' ' + last + ', and I am ' + str(age)
'my name is Jon Doe, and I am 23'
>>> 'I am ' + age + ' years old!'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: must be str, not int
>>> f'I am {age} years old! f-strings RULE!!'
'I am 23 years old! f-strings RULE!!'