Skip to main content

Strings

String Interpolation

String interpolation is a process substituting values of variables into placeholders in a string. For instance, if you have a template for saying hello to a person like "Hello {Name of person}, nice to meet you!", you would like to replace the placeholder for name of person with an actual name. This process is called string interpolation.

f-strings (formatted strings)

Python supports multiple ways to format text strings. These include %-formatting [1], str.format() [2], and string.Template [3]. Each of these methods have their advantages, but in addition have disadvantages that make them cumbersome to use in practice. This PEP proposed to add a new string formatting mechanism: Literal String Interpolation. In this PEP, such strings will be referred to as "f-strings", taken from the leading character used to denote such strings, and standing for "formatted strings".

F-strings provide a way to embed expressions inside string literals, using a minimal syntax. It should be noted that an f-string is really an expression evaluated at run time, not a constant value. In Python source code, an f-string is a literal string, prefixed with 'f', which contains expressions inside braces. The expressions are replaced with their values.

>>> import datetime
>>> name = 'Fred'
>>> age = 50
>>> anniversary = datetime.date(1991, 10, 12)
>>> f'My name is {name}, my age next year is {age+1}, my anniversary is {anniversary:%A, %B %d, %Y}.'
'My name is Fred, my age next year is 51, my anniversary is Saturday, October 12, 1991.'
>>> f'He said his name is {name!r}.'
"He said his name is 'Fred'."

str.format()

String format() Parameters format() method takes any number of parameters. But, is divided into two types of parameters:

  • Positional parameters - list of parameters that can be accessed with index of parameter inside curly braces {index}
  • Keyword parameters - list of parameters of type key=value, that can be accessed with key of parameter inside curly braces {key}

For positional arguments

python-format-positional-argument source: https://www.programiz.com/python-programming/methods/string/format

For keyword arguments

python-format-keyword-argument source: https://www.programiz.com/python-programming/methods/string/format

raw string

The r means that the string is to be treated as a raw string, which means all escape codes will be ignored. For an example: '\n' will be treated as a newline character, while r'\n' will be treated as the characters \ followed by n.

reference