<jupyter_start><jupyter_text>String FormattingThere are four main ways to do jobs of string formatting:1. `+`2. `% formatting`3. `format` function4. `f-strings` `+`<jupyter_code>first_name = 'Faris'
last_name = 'Shi'
sport_name = 'basketball'

# it is ok
print(first_name + ' ' + last_name)

# it is not recommended
print(first_name + ' ' + last_name + ' love playing ' + sport_name)<jupyter_output><empty_output><jupyter_text>`% formatting`Before Python 3.6, we always concatenate string by using `% formatting`.But actually, `% formatting` is not recomended by [Python Doc](https://docs.python.org/3/library/stdtypes.htmlprintf-style-string-formatting) due to:1. it is verbose when a lot need to be concatenated together. can lead to error and makes code unreadable 2. it can not display tuples or dictionaries correctly<jupyter_code># it is ok
print('%s %s love playing %s'%(first_name, last_name, sport_name))

#it is not recommended, it is not easy to read it.
career = 'developer'
language = 'Python'
print('Hello %s %s, you are a %s, your favorite langauge is %s, and also love playing %s'%(first_name, last_name, career, language, sport_name))<jupyter_output><empty_output><jupyter_text>`format` functionstring.format function is the improvement of `% formatting` that it uses normal function call syntax and can be extensible through implementing `__format__` function to make `object` converting to stringHowever, it also have the same issue(readability) with `% formatting` unless you use dictionary to fix that.<jupyter_code>## normal way
print('Hello {} {} love playing {}'.format(first_name, last_name, sport_name))

## can specify the order by referecing the index
print('Hello {1} {2} love playing {0}'.format(sport_name, first_name, last_name))

#can specifiy the name like keyword arguments
print('Hello {first_name} {last_name} love playing {sport_name}'.format(sport_name=sport_name, first_name=first_name, last_name=last_name))

## and we can operate dictionary
person = {'name': 'Faris', 'age': 30}
print('Hello, {}. You are {}'.format(person["name"], person["age"]))

## can do it like **kwargs
print('Hello, {name}. You are {age}'.format(**person))<jupyter_output><empty_output><jupyter_text>`f strings`It also uses the `__format__` protocol, and makes string-formatting easier. Just need keep `f` keyword in the beginning.`f-strings` is faster than both `format` function and `% formatting` since it is evaluated at runtime rather than constant values.<jupyter_code>print(f'Hello {first_name} {last_name} love playing {sport_name}')<jupyter_output><empty_output>
StarcoderdataJupyterStructuredCleanDedup