Programming Essentials Python - Predefined Functions - Formatting Strings

Let us understand how we can replace placeholders in Python using different variations of formatting strings. While we can concatenate strings, it will by default fail when we try to concatenate a string with a non-string. Conventionally, we tend to use str to convert the data type of the non-string values being concatenated to a string. From Python 3, they have introduced placeholders using {} within a string. We can replace placeholders either by name or by position.

Using placeholders will improve the readability of the code and is highly recommended.

print('Hello World')
print('Hello' + ' ' + 'World')

# This will fail as we are trying to concatenate 0 to a string

print('Hello' + 0 + 'World')
print('Hello' + str(0) + 'World')
i = 0

print('Hello' + str(i) + 'World')

# Replacing placeholders by name
i = 0

print(f'Hello{i}World')

# Replacing placeholders by name
print('Hello{i}World'.format(i=0))

# Replacing placeholders by position
print('Hello{}World'.format(0))

# Replacing placeholders by position
print('Hello{}World{}'.format(0, 1))

# These are the approaches which are commonly used
i = 0
s1 = f'str1: Hello{i}World'
print(s1)

s2 = 'str2: Hello{j}World'.format(j=i)
print(s2)
It is recommended to use the placeholder approach over concatenating using `+`.

Key Concepts Explanation

String Concatenation

In Python, string concatenation can be done using the + operator. However, when trying to concatenate a string with a non-string value, it will result in a TypeError. To resolve this, we can convert non-string values to string using the str() function.

Placeholders in Strings

Python 3 introduced a way to include placeholders {} in strings for later substitution of values during runtime. Placeholders can be replaced using either positional or named arguments. The f-string format allows direct variable substitution within the string, while the format() method and positional placeholders provide flexibility in string formatting.

Hands-On Tasks

  1. Implement string concatenation using the + operator.
  2. Replace placeholders in strings using positional and named arguments.

Conclusion

In conclusion, using placeholders in strings is a more efficient and readable approach compared to string concatenation. By mastering the concept of placeholders, you can enhance the quality of your Python code and make it more maintainable. Practice the provided examples and explore further to solidify your understanding.

Watch the video tutorial here