DEV Community

≀Paulo Portela
≀Paulo Portela

Posted on

Working with Strings in Python

Python has powerful built-in support for working with strings. In this post, we'll explore some of the most commonly used string operations, including creating strings, concatenating and repeating strings, changing the case of strings, replacing characters, splitting strings, checking for the existence of words, and formatting strings, all while applying an astronomy theme.

Creating Strings

In Python, you can create strings using single, double, or triple quotes. Here's an example of creating a one-line string and a multi-line string representing the name and description of a planet:

# One-line string planet_name = "Mars" print(f"Planet name: {planet_name}") # Output: Planet name: Mars 
Enter fullscreen mode Exit fullscreen mode
# Multi-line string planet_description = """Mars is the fourth planet from the Sun and the second-smallest planet in the Solar System, being larger than only Mercury. Named after the Roman god of war, it is often referred to as the "Red Planet" because the iron oxide prevalent on its surface gives it a reddish appearance.""" print(f"Planet description: {planet_description}") Output: Planet description: Mars is the fourth planet from the Sun and the second-smallest planet in the Solar System, being larger than only Mercury. Named after the Roman god of war, it is often referred to as the "Red Planet" because the iron oxide prevalent on its surface gives it a reddish appearance. 
Enter fullscreen mode Exit fullscreen mode

Concatenating and Repeating Strings

You can concatenate strings using the + operator, and repeat strings using the * operator. Here's an example of concatenating and repeating strings to create a sentence about the number of moons of a planet:

# Concatenating strings planet_name = "Mars" num_moons = 2 sentence = planet_name + " has " + str(num_moons) + " moons." print(sentence) # Output: Mars has 2 moons. 
Enter fullscreen mode Exit fullscreen mode
# Repeating strings separator = "-" print(separator * 10) # Output: ---------- 
Enter fullscreen mode Exit fullscreen mode

Changing the Case of Strings

You can change the case of a string using the upper, lower, capitalize, and title methods. Here's an example of changing the case of a string representing the name of a planet:

# Convert to uppercase planet_name = "Mars" print(planet_name.upper()) # Output: MARS 
Enter fullscreen mode Exit fullscreen mode
# Convert to lowercase print(planet_name.lower()) # Output: mars 
Enter fullscreen mode Exit fullscreen mode
# Convert to capitalization print(planet_name.capitalize()) # Output: Mars 
Enter fullscreen mode Exit fullscreen mode
# Convert to title case print(planet_name.title()) # Output: Mars 
Enter fullscreen mode Exit fullscreen mode

Replacing Characters

You can replace characters in a string using the replace method. Here's an example of replacing characters in a string representing the name of a planet:

# Replace characters planet_name = "Mars" new_planet_name = planet_name.replace("M", "C") print(new_planet_name) # Output: Cars 
Enter fullscreen mode Exit fullscreen mode

Splitting and Slicing Strings

You can split the contents of a string using the split method. By default, split splits a string on whitespace, but you can also specify a different separator. Here's an example of splitting a string representing the names of planets, and extracting the domain from an email address:

# Split the contents of a string planets = "Mercury Venus Earth Mars Jupiter Saturn Uranus Neptune" planet_list = planets.split() print(planet_list) # Output: ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune'] 
Enter fullscreen mode Exit fullscreen mode
# Split using a different separator planets = "Mercury,Venus,Earth,Mars,Jupiter,Saturn,Uranus,Neptune" planet_list = planets.split(sep=",") print(planet_list) # Output: ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune'] 
Enter fullscreen mode Exit fullscreen mode
# Extract the domain from an email address email = "astronomer@example.com" domain = email.split(sep="@") print(domain[1]) # Output: example.com 
Enter fullscreen mode Exit fullscreen mode

Strings can be sliced using the slice() function or using square brackets. The syntax for slicing isstring[start:stop:step], where start is the starting index, stop is the ending index (exclusive), and step is the step size. If start is omitted, slicing starts from the beginning of the string. If stop is omitted, slicing goes to the end of the string. If step is omitted, the step size is 1:

planet = 'Mars' print(planet[1:]) # Output: ars print(planet[2:3]) # Output: r print(planet[:-1]) # Output: Mar sliced = slice(1, 3) print(planet[sliced]) # Output: ar 
Enter fullscreen mode Exit fullscreen mode

Checking for the Existence of Words

You can check for the existence of a word in a string using the in keyword. Here's an example of checking for the existence of a word in a string representing a sentence about a planet:

# Check for the existence of a word sentence = "Mars is the fourth planet from the Sun." word = "Mars" if word in sentence: print(f"{word} is in the sentence.") else: print(f"{word} is not in the sentence.") # Output: Mars is in the sentence. 
Enter fullscreen mode Exit fullscreen mode
print("Mars" in "Mars is the fourth planet from the Sun.") # Output: True 
Enter fullscreen mode Exit fullscreen mode

Obtaining the Number of Occurrences of a Word

You can obtain the number of occurrences of a word in a string using the count method. Here's an example of obtaining the number of occurrences of a word in a string representing a sentence about a planet:

# Obtain the number of occurrences of a word sentence = "Mars is the fourth planet from the Sun. Mars has two moons." word = "Mars" count = sentence.count(word) print(f"{word} occurs {count} times in the sentence.") # Output: Mars occurs 2 times in the sentence. 
Enter fullscreen mode Exit fullscreen mode

Formatting Strings

You can format strings using the format method or string interpolation (f-strings). Here's an example of formatting a string using the format method and string interpolation, with one or more inputs:

# Format a string using the format method planet_name = "Mars" num_moons = 2 sentence = "{} has {} moons.".format(planet_name, num_moons) print(sentence) # Output: Mars has 2 moons. 
Enter fullscreen mode Exit fullscreen mode
# Format a string using string interpolation planet_name = "Mars" num_moons = 2 sentence = f"{planet_name} has {num_moons} moons." print(sentence) # Output: Mars has 2 moons. 
Enter fullscreen mode Exit fullscreen mode
# Format a string with multiple inputs planet1_name = "Earth" planet2_name = "Mars" sentence = f"{planet1_name} and {planet2_name} are neighbouring planets." print(sentence) # Output: Earth and Mars are neighbouring planets. 
Enter fullscreen mode Exit fullscreen mode

Removing Prefixes and Suffixes

You can remove prefixes and suffixes from a string using the removeprefix and removesuffix methods. Here's an example of removing a prefix and a suffix from a string representing the name of a planet:

# Remove a prefix planet_name = "Planet Mars" new_planet_name = planet_name.removeprefix("Planet ") print(new_planet_name) # Output: Mars 
Enter fullscreen mode Exit fullscreen mode
# Remove a suffix planet_name = "Mars Planet" new_planet_name = planet_name.removesuffix(" Planet") print(new_planet_name) # Output: Mars 
Enter fullscreen mode Exit fullscreen mode

Checking if a String Starts with a Certain Word

You can check if a string starts with a certain word or words using the startswith method. Here's an example of checking if a string representing a sentence about a planet starts with a certain word:

# Check if a string starts with a certain word sentence = "Mars is the fourth planet from the Sun." word = "Mars" if sentence.startswith(word): print(f"The sentence starts with {word}.") else: print(f"The sentence does not start with {word}.") # Output: The sentence starts with Mars. 
Enter fullscreen mode Exit fullscreen mode

Stripping Strings

You can strip whitespace or other characters from the beginning and end of a string using the strip, lstrip, and rstrip methods. Here's an example of stripping whitespace from a string representing the name of a planet:

# Strip whitespace from the beginning and end of a string planet_name = " Mars " stripped_planet_name = planet_name.strip() print(stripped_planet_name) # Output: Mars 
Enter fullscreen mode Exit fullscreen mode
# Strip whitespace from the beginning of a string planet_name = " Mars " stripped_planet_name = planet_name.lstrip() print(stripped_planet_name) # Output: Mars 
Enter fullscreen mode Exit fullscreen mode
# Strip whitespace from the end of a string planet_name = " Mars " stripped_planet_name = planet_name.rstrip() print(stripped_planet_name) # Output: Mars 
Enter fullscreen mode Exit fullscreen mode

Using f-strings

You can use f-strings to format strings in a concise and readable way. Here's an example of using f-strings to format strings representing various astronomical quantities:

import datetime # Format a string using f-strings w = 0.1 x = 2 n = 1234567890 now = datetime.datetime.now() 
Enter fullscreen mode Exit fullscreen mode
# Display the value of an expression print(f"{w = }") # Output: w = 0.1 print(f"{x % 2 = }") # Output: x % 2 = 0 
Enter fullscreen mode Exit fullscreen mode
# Format a number with underscores as a thousand separator print(f"{n:_}") # Output: 1_234_567_890 
Enter fullscreen mode Exit fullscreen mode
# Align values print(f"{w:>20}") # Output: 0.1 print(f"{w:<20}") # Output: 0.1 print(f"{w:^20}") # Output: 0.1 
Enter fullscreen mode Exit fullscreen mode
# Fill and align values print(f"{w:_>20}") # Output: _________________0.1 print(f"{w:_<20}") # Output: 0.1_________________ print(f"{w:_^20}|") # Output: ________0.1_________| 
Enter fullscreen mode Exit fullscreen mode
# Format dates print(f"{now = :%Y-%m-%d}") # Output: now = 2024-02-18 print(f"{now = :%c}") # Output: now = Sun Feb 18 00:32:09 2024 print(f"{now = :%I%p}") # Output: now = 12AM 
Enter fullscreen mode Exit fullscreen mode

Converting Strings

You can convert strings to other types using various functions, including ascii, repr, and str. Here's an example of converting a string representing the name of a planet to ASCII, using the repr function to display the string representation of an object, and converting a number to a string:

# Convert a string to ASCII planet_name = "Mars" ascii_planet_name = ascii(planet_name) print(ascii_planet_name) # Output: 'Mars' 
Enter fullscreen mode Exit fullscreen mode
# Display the string representation of an object w = "Mars" print(f"{w!r}") # Output: 'Mars' 
Enter fullscreen mode Exit fullscreen mode
# Convert a number to a string num_moons = 2 str_num_moons = str(num_moons) print(str_num_moons) # Output: 2 
Enter fullscreen mode Exit fullscreen mode

In conclusion, Python provides rich built-in operations for working with strings.

Top comments (0)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.