As a data scientist, you would use it for inserting a title in a graph, show a message or an error, or pass a statement to a function.
Methods for Formatting
Positional formatting
Formatted string literals
Template method
String.Format Method
We put placeholders defined by a pair of curly braces in a text. We call the string dot format method. Then, we pass the desired value into the method. The method replaces the placeholders using the values in the order of appearance replace by value:
We can use variables for both the string and the values passed to the method. In the below example code, we define a string with placeholders and two other variables. We apply the format method to the string using the two defined variables. The method reads the string and replaces the placeholders with the given values.
In the below example, you add index numbers into the placeholders to reorder values. This affects the order in which the method replaces the placeholders.
The method replaces them with the values in the given order.
print("{} has a friend called {} and a sister called {}".format("Betty","Linda","Daisy"))
We can also introduce keyword arguments that are called by their keyword name.
In the example code below, we inserted keywords in the placeholders. Then, we call these keywords in the format method. We then assign which variable will be passed for each of them, resulting in the following output.
tool="Unsupervised algorithms"
goal="patterns"print("{title} try to find {aim} in the dataset".format(title=tool, aim=goal))
We want to insert their values in a string. Inside the placeholders, we can specify the value associated with the key tool of the variable data using bracket notation. Data is the dictionary specified in the method, and tool is the key present in that dictionary.
print('{data[tool]} try to find {data[goal]} in the dataset'.format(data=my_methods))
We can also specify the format specifies inside curly braces. This defines how individual values are presented. Here, we’ll use the syntax index colon specifier. One of the most common format specifiers is float represented by f. In the code, we specify that the value passed with the index 0 will be a float.
print("Only {0:f}% of the {1} produced worldwide is {2}!".format(0.5155675,"data","analyzed"))
But since the format returned is very particular, you could use the format specifier such as %y-%m-%d-%h-%m to adjust the format to something more familiar to us!
print("Today's date is {:%Y-%m-%d %H:%M}".format(datetime.now()))
In the following example, you will assign the substrings going from the 4th to the 19th character, and from the 22nd to the 44th character of wikipedia_article to the variables first_pos and second_pos, respectively. Adjust the strings so they are lowercase. Finally, print the variables first_pos and second_pos.
# Assign the substrings to the variables
first_pos = wikipedia_article[3:19].lower()
second_pos = wikipedia_article[21:44].lower()
In this tutorial, you'll learn all about Python Strings: slicing and striding, manipulating and formatting them with the Formatter class, f-strings, templates and more!
Learn about the f-string formatting technique in Python 3.6. In this tutorial, you'll see what advantages it offers and go through some example use cases.
Zanurz się w data science z Pythonem i naucz się skutecznie analizować oraz wizualizować dane. Nie potrzeba doświadczenia ani umiejętności programowania.
String formatting is also known as String interpolation. It is the process of inserting a custom string or variable in predefined text.
As a data scientist, you would use it for inserting a title in a graph, show a message or an error, or pass a statement to a function.
Methods for Formatting
String.Format Method
We put placeholders defined by a pair of curly braces in a text. We call the string dot format method. Then, we pass the desired value into the method. The method replaces the placeholders using the values in the order of appearance replace by value:
Positional Formatting
We define a string and insert two placeholders. We pass two strings to the method, which will be passed to get the following output:
We can use variables for both the string and the values passed to the method. In the below example code, we define a string with placeholders and two other variables. We apply the format method to the string using the two defined variables. The method reads the string and replaces the placeholders with the given values.
Reordering Values
In the below example, you add index numbers into the placeholders to reorder values. This affects the order in which the method replaces the placeholders.
The method replaces them with the values in the given order.
If we add the index numbers, the replacement order changes accordingly.
Name Placeholders
We can also introduce keyword arguments that are called by their keyword name.
In the example code below, we inserted keywords in the placeholders. Then, we call these keywords in the format method. We then assign which variable will be passed for each of them, resulting in the following output.
Let's examine this code below. We have defined a dictionary with keys: tool and goal.
We want to insert their values in a string. Inside the placeholders, we can specify the value associated with the key tool of the variable data using bracket notation. Data is the dictionary specified in the method, and tool is the key present in that dictionary.
So, we get the desired output shown below. Be careful! You need to specify the index without using quotes.
Format Specifier
We can also specify the format specifies inside curly braces. This defines how individual values are presented. Here, we’ll use the syntax index colon specifier. One of the most common format specifiers is float represented by
f. In the code, we specify that the value passed with the index 0 will be a float.We could also add
.2findicating that we want the float to have two decimals, as seen in the resulting output.Formatting
datetimePython has a module called datetime that allows us to, for example, to get the time and date for today.
But since the format returned is very particular, you could use the format specifier such as
%y-%m-%d-%h-%mto adjust the format to something more familiar to us!Interactive Example
In the following example, you will assign the substrings going from the 4th to the 19th character, and from the 22nd to the 44th character of
wikipedia_articleto the variablesfirst_posandsecond_pos, respectively. Adjust the strings so they are lowercase. Finally, print the variablesfirst_posandsecond_pos.When we run the above code, it produces the following result:
computer science artificial intelligenceTry it for yourself.
To learn more about positional formatting, please see this video from our course, Regular Expressions in Python.
This content is taken from DataCamp’s Regular Expressions in Python course by Maria Eugenia Inzaugarat.
Check out our Python String Tutorial.