String Formatting in Python

String Formatting in Python

Learn the different ways to implement str.format() in your code

Have you ever seen the str.format method in a code and never understood how it works? I'll breakdown how to use it in your code with several easy to understand examples.

Definition of the str.format() method

Here's another string method in python which works with the use of placeholders "{}".

These placeholders are represented as curly brackets which are meant to hold values indicated in format().

#Example
print("John Wesly drove to {} on Sunday".format("Manchester"))

#output
'John Wesly drove to Manchester on Sunday'
#"info" passed as string before "format"
#Whatever that must be passed before "format" must be only a string and no other datatype.
info = "John Wesley drove to {} on Sunday"
print(info.format("Manchester"))

#output
'John Wesley drove to Manchester on Sunday'

Above is an example that follows the syntax string.format(Argument)

string - "John Wesley drove to {} on Sunday" In the same string, you'll find the placeholder.

Also, there has to be an argument which will be passed into the placeholder. This argument can be recognized as a tuple of value or values.

Using a Variable in your str.format() method

A variable can also be passed as an argument. The variable can be of any datatype such as strings, float, integer etc.

# "info" passed as a variable
info = "John Wesley drove to Manchester on Sunday"
print("I knew {}".format(info))

#output
'I knew John Wesley drove to Manchester on Sunday'

Using Multiple Placeholders

Multiple placeholders can be used but the tuple of values will be positional arguments. What does this mean? 1st placeholder == 1st argument 2nd placeholder == 2nd argument

#Example
print("John Wesly drove to {} on Sunday and went to collect his pizza at {}".format("Manchester", "Mcdonnalds"))

#output
'John Wesly drove to Manchester on Sunday and went to collect his pizza at Mcdonnalds'

What if you prefer to switch the arguments?

Recall that the values of tuple are indexed starting from zero(0),1,2 etc. Placing the index as an argument in a placeholder you prefer allows you to switch.

#Example
print("John bought {0} oranges, {1} bananas and {2} apples".format(5,6,8))

#output
'John bought 5 oranges, 6 bananas and 8 apples'
#Positions changed
print("John bought {1} oranges, {2} bananas and {0} apples".format(5,6,8))

#output
'John bought 6 oranges, 8 bananas and 5 apples'
# Repeating an index
print("John bought {0} oranges, {1} bananas and {1} apples".format(5,6,8))

#ouput
'John bought 5 oranges, 6 bananas and 6 apples'

Using Keyword Arguments

Just as in user-defined functions, keyword arguments are also used in the str.format() method.

#Example
print("John studied hard for {subject} and got an {grade}".format(subject = "English", grade = "A"))

#output
'John studied hard for English and got an A'
#Ignore the grammatical structure of the output
print("John studied hard for {grade} and got an {subject}".format(subject = "English", grade = "A"))

#output
'John studied hard for A and got an English'

Mixing the positional and keyword arguments

#Example
print("John studied hard for {0} and got an {grade}".format("English", grade = "A"))

#output
'John studied hard for English and got an A'
#Positional aruguments comes before the keyword argument
print("John studied hard for {grade} and got an {0}".format("English", grade = "A"))

#output
'John studied hard for A and got an English'
#This will raise an error because the keyword argument came before the postional argument.
print("John studied hard for {grade} and got an {0}".format(grade = "A", "English"))

#output
 File "<ipython-input-35-f30fce4c34b2>", line 2
    "John studied hard for {grade} and got an {0}".format(grade = "A", "English")
                                                                       ^
SyntaxError: positional argument follows keyword argument

Conclusion

String formatting with the str.format() method makes your code appealing to a reader. You can visit w3schools, realpython, geeksforgeeks to see more amazing tasks you can carry out with the str.format()method. You'll be shocked at the number of things you can try out with this method.