Tips on Python String

ifeelfree
4 min readAug 3, 2023

--

1. Introduction

Python strings are fundamental data types in coding. This concise article offers essential string tips, enhancing your string manipulation skills.

2. The format method

The str.format() method in Python is used for string formatting and inserting values into placeholders within a string. It provides a flexible and powerful way to create strings with dynamic content. The following codes illustrate 5 typical use cases for the format method:

  • basic placeholder replacement
  • positional arguments
  • keyword arguments
  • alignment and padding for string
  • alignment and padding for number
# 1. Basic Placeholder Replacement:
print('The {} {} {}'.format('car','yellow','fast')) #empty braces
The car yellow fast

# 2. Positional Arguments:
print('The {2} {1} {0}'.format('car','yellow','fast')) #index
The fast yellow car

# 3. Keyword Arguments:
print('The {f} {y} {c}'.format(c='car',y='yellow',f='fast')) #keywords
The fast yellow car

# 4. Alignment and Padding for string
# :<10 means left-aligned with a width of 10 characters
formatted_string = "{:<10} {:<10}".format("Name", "Age")
print(formatted_string) # Output: "Name Age

# 5. Alignment and padding for number
# 5.1 {:.nf} float
pi = 3.14159
formatted_string = "Value of pi: {:.2f}".format(pi)
print(formatted_string) # Output: "Value of pi: 3.14"
# 5.2 {:0n} interger
number = 42
formatted_number = "Number: {:04}".format(number)
print(formatted_number) # Output: "Number: 0042"

3. The f-string method

An f-string, short for “formatted string literal,” is a feature introduced in Python 3.6 that provides a concise and convenient way to embed expressions inside string literals. F-strings are a powerful tool for string formatting and interpolation, making it easier to create strings with dynamic content. They are denoted by the f prefix before the opening quote of a string. Here we list four common usages of this method:

  • variable interpretation
  • function call
  • string alignment and padding
  • number alignment and padding
# 1. Variable interpretation 
name = "Alice"
age = 30
formatted_string = f"Name: {name}, Age: {age}"
print(formatted_string) # Output: "Name: Alice, Age: 30"

# 2. Function call
def some_function():
return 'some string'
my_str = f"{some_function()} is funny!" # Outputs: "some string is funny!"


# 3. String alignment and padding
langs = ["LISP", "C", "MATLAB", "R"]
released = [1958, 1972, 1984, 1993]
print(f"{'Language':<10} {'Release date':<15}")
for lang, auth, date in zip(langs, released):
print(f"{lang:<10} {date:<15}")
# Outputs:
# Language Release date
# LISP 1958
# C 1972
# MATLAB 1984
# R 1993

# 4. Number alignment and padding
pi = 3.14159
formatted_string = f"Value of pi: {pi:.2f}"
print(formatted_string) # Output: "Value of pi: 3.14"

In f-string method, sometimes you will meet with the !r format. For example,

name = "Alice"
formatted_string = f"Name: {name!r}"
print(formatted_string) # Output: "Name: 'Alice'"

In this example, the !r specifier is used to include the repr() representation of the name variable within the formatted string. The single quotes around 'Alice' indicate that it's the repr() representation of the string.

Using !r can be particularly useful when you want to ensure that the representation of a variable is displayed as-is, especially when dealing with complex or special characters that might not be immediately obvious in their regular string form. The !reffect of can be observed in the following example:

    class Comedian:
def __init__(self, first_name, last_name, age):
self.first_name = first_name
self.last_name = last_name
self.age = age

def __str__(self):
return f"{self.first_name} {self.last_name} is {self.age}."

def __repr__(self):
return f"{self.first_name} {self.last_name} is {self.age}. Surprise!"


new_comedian = Comedian("Eric", "Idle", "74")
print(f"{new_comedian}") # Output: Eric Idle is 74.
print(f"{new_comedian!r}") # Output: Eric Idle is 74. Surprise!

4. The Template method

The method is deprecated.

The string.Template class is another way to perform string interpolation and variable substitution in Python. However, with the introduction of f-strings (formatted string literals) in Python 3.6, f-strings have become a more concise, expressive, and preferred way to achieve similar functionality. In most cases, you can replace the use of string.Template with f-strings.

from string import Template

name = "Alice"
age = 30

template = Template("Name: $name, Age: $age")
formatted_string = template.substitute(name=name, age=age)
print(formatted_string) # Output: "Name: Alice, Age: 30"

However, there might be situations where string.Template could still be useful, especially when working with user-generated templates or when you want to separate variable substitution from the template itself. It's also worth noting that string.Template provides some additional features, such as customizing the placeholder syntax or allowing for safer substitution in cases where security is a concern.

5. The % operator

The method is deprecated.

The % operator, often referred to as the "string formatting operator" or "string interpolation operator," is an older method of string formatting in Python. While it's still valid and functional, it has been largely superseded by more modern approaches like f-strings (introduced in Python 3.6) and the .format() method.

name = "Alice"
age = 30
formatted_string = "Name: %s, Age: %d" % (name, age)
print(formatted_string) # Output: "Name: Alice, Age: 30"

# Here are some common formatting codes you can use with the % operator:
# %s: String
# %d: Integer
# %f: Float
# %x: Hexadecimal (integer)
# %o: Octal (integer)

6. Bytes and unicode

The method is deprecated.

In contemporary Python (Python 3.0 and later), Unicode takes the forefront as the primary string type, ensuring uniform management of both ASCII and non-ASCII text. In earlier Python iterations, strings were confined to bytes, lacking explicit Unicode encoding.

For transformation, the Unicode string seamlessly transitions to its UTF-8 byte representation via the encode method:

unicode_text = val.encode('utf-8')
str_result = unicode_text.decode('utf-8')

7. Miscellaneous

  • Special characters should be after ** \ ** symbol
my_str = f"The \"comedian\" is {name}, aged {age}." 
# Output: "The 'comedian is li, aged 34."
  • Multiple strings
message = f"""
hello
the
world!"""
print(message)

# hello
# the
# world!

--

--