10 Awesome Python String Tricks

10 Awesome Python String Tricks
Photo by Artturi Jalli / Unsplash

A string is a sequence of characters. In Python, strings are immutable, which means that once created, they cannot be changed. Strings are surrounded by either single quotation marks, or double quotation marks. Here are some of the most useful string methods in Python.

1. Formatted Strings

f'' strings are formatted string literals, which are string literals that have an f at the beginning and curly braces containing expressions that will be replaced with their values. The expressions are evaluated at run time, not at compile time. This is why f'' strings are also called formatted string literals. Here is an example:

name = 'John'
age = 23
print(f'Hello, my name is {name} and I am {age} years old.')

2. Reverse a String

To reverse a string, you can use the extended slice syntax with step value -1. This tells Python to start at the end of the string and move backwards, one character at a time. Here is an example:

string = 'Hello World'
print(string[::-1])

3. Multiline Strings

Multiline strings are surrounded by triple quotes. They can span multiple lines and have all the features of normal strings. Here is an example:

string = '''This is a multiline string.
It can span multiple lines.'''
print(string)

4. String Repetition

To repeat a string, you can use the * operator. Here is an example:

string = 'Hello World'
print(string * 2)
# Hello WorldHello World

5. Aligning Strings

You can use the <, ^, and > characters to align text to the left, center, or right within a field, respectively. For example:

name = "John"
age = 30

# align text to the left
message = "Hello, my name is {:<10} and I am {:<3} years old".format(name, age)
print(message)  # prints "Hello, my name is John      and I am 30  years old"

# align text to the center
message = "Hello, my name is {:^10} and I am {:^3} years old".format(name, age)
print(message)  # prints "Hello, my name is   John    and I am  30 years old"

# align text to the right
message = "Hello, my name is {:>10} and I am {:>3} years old".format(name, age)
print(message)  # prints "Hello, my name is      John and I am   30 years old"

7. Padding Strings

You can use the 0 character to pad numbers with zeros. For example:

number = 42

# pad number with 3 zeros
formatted_number = "{:03d}".format(number)
print(formatted_number)  # prints "042"

8. Truncating Strings

You can use the . character to truncate text to a certain number of characters. For example:

string = "This is a very long string"

# truncate string to 10 characters
truncated_string = "{:.10}".format(string)
print(truncated_string)  # prints "This is a"

9. Expand Tabs

`expandtabs() function expands tabs in a string to a certain number of spaces. By default, tabs are expanded to 8 spaces, but you can specify a different number of spaces if desired. For example:

string = "Hello\tWorld"
expanded_string = string.expandtabs()
print(expanded_string)  # prints "Hello     World"

# expand tabs to 4 spaces
expanded_string = string.expandtabs(4)
print(expanded_string)  # prints "Hello World"

10. isascii()

This one is super handy. `isascii() function returns True if all the characters in a string are ASCII characters, and False otherwise. ASCII characters are a set of 128 characters that includes the digits, letters, and special characters that are commonly used in English. For example:

string1 = "Hello, World!"
is_ascii = string1.isascii()
print(is_ascii)  # prints True

string2 = "ใ“ใ‚“ใซใกใฏ"
is_ascii = string2.isascii()
print(is_ascii)  # prints False

Bonus: translate()

The `translate() function returns a copy of the string in which each character has been mapped through a translation table. The translation table is created using the maketrans() function. Here is an example:

string = "Hello, World!"
translation_table = str.maketrans("aeiou", "12345")
translated_string = string.translate(translation_table)
# translated_string = "H2ll4, W4rld!"

Conclusion

In this article, we learned about some of the most useful string methods in Python. We learned how to use f'' strings, reverse a string, create multiline strings, repeat a string, align strings, pad strings, truncate strings, expand tabs, and check if a string is ASCII. We also learned how to use the translate() function to translate characters in a string. If you enjoyed this article, please share it with your friends and colleagues. Thanks for reading!