Mastering Python: Understanding Strings and Formatting
Written on
Chapter 1: Introduction to String Manipulation
In Python, enhancing the readability of code can be achieved by incorporating spaces, tabs, and newline characters into strings. This chapter delves into how these elements can improve your coding experience.
This paragraph will result in an indented block of text, typically used for quoting other text.
Section 1.1: Utilizing Tabs and Newlines
Using the print function, we can display strings on the screen. For example:
>>> print("Medium")
Medium
>>> print("\tMedium")
Medium
>>> print("\nMedium")
Medium
By placing t or n at the beginning of a string, you create a tab space or a newline, respectively. Try predicting the output of the following examples:
>>> print("Companies:\nMedium\nSubstack\nFacebook")
Companies:
Medium
Substack
>>> print("Companies:\n\tMedium\n\tSubstack\n\tFacebook")
Companies:
Medium
Substack
Section 1.2: Trimming Spaces
To eliminate spaces from either side of a string, you can use the lstrip() and rstrip() methods. For instance:
>>> favorite_snake = 'python '
>>> favorite_snake
'python '
>>> favorite_snake.rstrip()
'python'
>>> favorite_snake
'python '
In this example, while rstrip() removes the trailing space, the original variable, favorite_snake, remains unchanged. To make this adjustment permanent, you can reassign the value:
>>> favorite_snake = 'python '
>>> favorite_snake = favorite_snake.rstrip()
>>> favorite_snake
'python'
The lstrip() method works similarly but targets the left side:
>>> favorite_snake = ' python '
>>> favorite_snake.rstrip()
' python'
>>> favorite_snake.lstrip()
'python '
Additionally, the strip() method removes spaces from both ends:
>>> favorite_snake = ' python '
>>> favorite_snake.strip()
'python'
Section 1.3: Removing Prefixes
Consider the following example using the removeprefix() method:
Notice how this method effectively removes the specified prefix from the string:
'.com'
Chapter 2: Additional Learning Resources
For those interested in expanding their knowledge of Python, check out the following video tutorials:
The first video, "Python for Beginners – Full Course [Programming Tutorial]," provides a comprehensive introduction to Python programming.
The second video, "Python Tutorial for Beginners 2: Strings - Working with Textual Data," focuses on string manipulation in Python, a key skill for any programmer.