(Tutorial) Python String format() – DataCamp

[ad_1]

String formatting is also called String interpolation. It is the method of inserting a customized string or variable in predefined textual content.

custom_string = "String formatting"
print(f"{custom_string} is a powerful technique")
String formatting is a robust method

As a data scientist, you’d use it for inserting a title in a graph, present a message or an error, or move an announcement to a perform.

Methods for formatting

  • Positional formatting
  • Formatted string literals
  • Template methodology

String.Format Method

We put placeholders outlined by a pair of curly braces in a textual content. We name the string dot format methodology. Then, we move the specified worth into the tactic. The methodology replaces the placeholders utilizing the values within the order of look change by worth:

'textual content{}'.format(worth)

Positional Formatting

We outline a string and insert two placeholders. We move two strings to the tactic, which will likely be handed to get the next output:

print("Machine learning provides {} the ability to learn {}".format("systems", "automatically"))
Machine studying gives methods the power to study robotically

We can use variables for each the string and the values handed to the tactic. In the beneath instance code, we outline a string with placeholders and two different variables. We apply the format methodology to the string utilizing the 2 outlined variables. The methodology reads the string and replaces the placeholders with the given values.

my_string = "{} rely on {} datasets"
methodology = "Supervised algorithms"
situation = "labeled"
print(my_string.format(methodology, situation))
Supervised algorithms depend on labeled datasets

Reordering Values

In the beneath instance, you add index numbers into the placeholders to reorder values. This impacts the order wherein the tactic replaces the placeholders.

The methodology replaces them with the values within the given order.

print("{} has a friend called {} and a sister called {}". format("Betty", "Linda", "Daisy"))
Betty has a good friend referred to as Linda and a sister referred to as Daisy

If we add the index numbers, the alternative order modifications accordingly.

print("{2} has a friend called {0} and a sister called {1}". format("Betty", "Linda", "Daisy"))
Daisy has a good friend referred to as Betty and a sister referred to as Linda

Name Placeholders

We may introduce key phrase arguments which can be referred to as by their key phrase identify.

In the instance code beneath, we inserted key phrases within the placeholders. Then, we name these key phrases within the format methodology. We then assign which variable will likely be handed for every of them, ensuing within the following output.

device="Unsupervised algorithms"
aim="patterns"
print("{title} try to find {aim} in the dataset".format(title=device, purpose=aim))
Unsupervised algorithms attempt to discover patterns within the dataset

Let’s look at this code beneath. We have outlined a dictionary with keys: device and aim.

my_methods = {"tool": "Unsupervised algorithms", "goal": "patterns"}

We need to insert their values in a string. Inside the placeholders, we are able to specify the worth related to the important thing device of the variable knowledge utilizing bracket notation. Data is the dictionary specified within the methodology, and power is the important thing current in that dictionary.

print('{knowledge[tool]} attempt to discover {knowledge[goal]} within the dataset'.format(knowledge=my_methods))

So, we get the specified output proven beneath. Be cautious! You have to specify the index with out utilizing quotes.

Unsupervised algorithms attempt to discover patterns within the dataset

Format Specifier

We may specify the format specifies inside curly braces. This defines how particular person values are offered. Here, we’ll use the syntax index colon specifier. One of the most typical format specifiers is float represented by f. In the code, we specify that the worth handed with the index Zero will likely be a float.

print("Only {0:f}% of the {1} produced worldwide is {2}!". format(0.5155675, "data", "analyzed"))
Only 0.515567% of the info produced worldwide is analyzed!

We might additionally add .2f indicating that we would like the float to have two decimals, as seen within the ensuing output.

print("Only {0:.2f}% of the {1} produced worldwide is {2}!".format(0.5155675, "data", "analyzed"))
Only 0.52% of the info produced worldwide is analyzed!

Formatting datetime

Python has a module referred to as datetime that enables us to, for instance, to get the time and date for at this time.

from datetime import datetime
print(datetime.now())
2020-08-08 06:28:42.715243

But for the reason that format returned could be very specific, you might use the format specifier reminiscent of %y-%m-%d-%h-%m to regulate the format to one thing extra acquainted to us!

print("Today's date is {:%Y-%m-%d %H:%M}".format(datetime.now()))
Today's date is 2020-08-08 06:29

Interactive Example

In the next instance, you’ll 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’re lowercase. Finally, print the variables first_pos and second_pos.

# Assign the substrings to the variables
first_pos = wikipedia_article[3:19].decrease()
second_pos = wikipedia_article[21:44].decrease()

When we run the above code, it produces the next consequence:

laptop science
artificial intelligence

Try it for your self.

To study extra about positional formatting, please see this video from our course, Regular Expressions in Python.

This content material is taken from DataCamp’s Regular Expressions in Python course by Maria Eugenia Inzaugarat.

[ad_2]

Source hyperlink

Write a comment