What is a string in Python?
A Python string string is an array of 16-bit Unicode bytes (and 8-bit ANSI bytes for Python 2), where each string character is represented by one byte. One character in Python is also a string of length 1. To access the characters in the string, use the square brackets "[]". A Python string is immutable, meaning that it cannot be changed once it is created. All string processing operations return a copy of the original string and do not modify it. A literal string can be enclosed in single, double, or triple quotes. The built-in Python "str" library supplies essential methods out of the box for searching, concatenating, reversing, splitting, comparing strings, and more.
What is Python f-string?
Python f-string is the new Python syntax for string formatting, available since Python 3.6. By using Python f-strings, you can format strings in a way that is faster, more readable, and less error-prone. In Python source code, the f-string is a literal string prefixed with "f" or "F" containing expressions inside "{}" brackets.
Python f-string Examples
Python f-strings are very flexible and powerful. You can learn more about f-strings on the officia PEP 498 website. Following are a few examples of using f-string in Python with short descriptions:
How to format numbers using f-strings?
In Python, f-strings support a "mini-format specification language" that gives us advanced formatting options for numbers. Below is an example formatting numbers using Python f-strings:
How to format date or time using f-strings?
You can format dates and times with f-strings in Python. Below is an example of printing the current date and time using Python f-strings:
How to make arithmetic operations using an f-string?
F-strings can be used to perform math operations. The following is an example of performing arithmetic operations on Python f-strings:
How to get list values by index using f-strings?
Python f-strings can read element values from lists and dictionaries. The following is an example of accessing a list element by its index.
How to access elements by object key using f-strings?
Using f-strings, you can access dictionary elements by a key:
How to use complex objects in f-string?
Python f-strings can call object methods:
How to call a function in f-strings?
Python f-strings can call global functions: