Working with Strings in Python
Tags: python, beginners, programming
Published: 2024-02-17 01:29:29

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:

```{python}
# One-line string
planet_name = "Mars"
print(f"Planet name: {planet_name}")

# Output: Planet name: Mars
```

```{python}
# 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.
```

## 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:

```{python}
# Concatenating strings
planet_name = "Mars"
num_moons = 2
sentence = planet_name + " has " + str(num_moons) + " moons."
print(sentence)

# Output: Mars has 2 moons.
```

```{python}
# Repeating strings
separator = "-"
print(separator * 10)

# Output: ----------
```

## 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:

```{python}
# Convert to uppercase
planet_name = "Mars"
print(planet_name.upper())

# Output: MARS
```

```{python}
# Convert to lowercase
print(planet_name.lower())

# Output: mars
```

```{python}
# Convert to capitalization
print(planet_name.capitalize())

# Output: Mars
```

```{python}
# Convert to title case
print(planet_name.title())

# Output: Mars
```

## 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:

```{python}
# Replace characters
planet_name = "Mars"
new_planet_name = planet_name.replace("M", "C")
print(new_planet_name)

# Output: Cars
```

## 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:

```{python}
# 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']
```

```{python}
# 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']
```

```{python}
# Extract the domain from an email address
email = "astronomer@example.com"
domain = email.split(sep="@")
print(domain[1])

# Output: example.com
```

Strings can be sliced using the `slice()` function or using square brackets. The syntax for slicing is` string[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:

```{python}
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
```

## 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:

```{python}
# 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.
```

```{python}
print("Mars" in "Mars is the fourth planet from the Sun.")

# Output: True
```

## 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:

```{python}
# 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.
```

## 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:

```{python}
# 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.
```

```{python}
# 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.
```

```{python}
# 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.
```

## 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:

```{python}
# Remove a prefix
planet_name = "Planet Mars"
new_planet_name = planet_name.removeprefix("Planet ")
print(new_planet_name)

# Output: Mars
```

```{python}
# Remove a suffix
planet_name = "Mars Planet"
new_planet_name = planet_name.removesuffix(" Planet")
print(new_planet_name)

# Output: Mars
```

## 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:

```{python}
# 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.
```

## 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:

```{python}
# 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
```

```{python}
# Strip whitespace from the beginning of a string
planet_name = "  Mars  "
stripped_planet_name = planet_name.lstrip()
print(stripped_planet_name)

# Output: Mars  
```

```{python}
# Strip whitespace from the end of a string
planet_name = "  Mars  "
stripped_planet_name = planet_name.rstrip()
print(stripped_planet_name)

# Output:   Mars
```

## 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:

```{python}
import datetime

# Format a string using f-strings
w = 0.1
x = 2
n = 1234567890
now = datetime.datetime.now()
```

```{python}
# Display the value of an expression
print(f"{w = }")  # Output: w = 0.1
print(f"{x % 2 = }")  # Output: x % 2 = 0
```

```{python}
# Format a number with underscores as a thousand separator
print(f"{n:_}")

# Output: 1_234_567_890
```

```{python}
# Align values
print(f"{w:>20}")  # Output:                  0.1
print(f"{w:<20}")  # Output: 0.1                 
print(f"{w:^20}")  # Output:         0.1         
```

```{python}
# 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_________|
```

```{python}
# 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
```

## 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:

```{python}
# Convert a string to ASCII
planet_name = "Mars"
ascii_planet_name = ascii(planet_name)
print(ascii_planet_name)

# Output: 'Mars'
```

```{python}
# Display the string representation of an object
w = "Mars"
print(f"{w!r}")

# Output: 'Mars'
```

```{python}
# Convert a number to a string
num_moons = 2
str_num_moons = str(num_moons)
print(str_num_moons)

# Output: 2
```

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