Understanding how to manipulate str() objects are essential for anyone working with Python. It’s important to know what tools you have at your disposal and how they work. Let’s use this quote from renowned mathematician John Tukey about being right and wrong as our example string

## “An approximate answer to the right question is worth a great deal more than a precise answer to the wrong question.” — John Tukey

### Let’s get started.

``````# Single quotes for single lined strings
s = "An approximate answer to the right question is worth a great deal more than a precise answer to the wrong question."
print(s)

# Output
An approximate answer to the right question is worth a great deal more than a precise answer to the wrong question.
# Triple quotes for multi-lined strings

s = """
An approximate answer to the right question
is worth a great deal more than
a precise answer to the wrong question.
"""
print(s)

# Output
An approximate answer to the right question
is worth a great deal more than
a precise answer to the wrong question.

# String can be sliced like [lists](https://docs.python.org/3/library/functions.html#func-list)
a = s[-40:-24]
print(a)

# Output

# Strings can be added and multiplied together
print(s[55:68] + s[30:35] + "?" * 3)

# Output
a great deal right???

# Splitting a string into a list of letters using list()
b = list(s[23:44])
print(b)

# Output
['t', 'o', ' ', 't', 'h', 'e', ' ', 'r', 'i', 'g', 'h', 't', ' ', 'q', 'u', 'e', 's', 't', 'i', 'o', 'n']

# Joining the letters together using join()
b = "".join(b)
print(b)

# Output
to the right question

# Splitting a string into a list of words using split()
a = a.split()
print(a)

# Output

# Joining list "a" with whitespace and adding " ", b, ".", and capitalizing
ab = (" ".join(a) + " " + b + ".").capitalize()
print(ab)

# Output
A precise answer to the right question.
``````
• Single quotes: ‘allows embedded “double” quotes’

• Double quotes: “allows embedded ‘single’ quotes”

With just a few builtin functions and string methods, you are already able to manipulate strings for a variety of tasks. There are a lot of string methods to choose from, and mastering each one could take seconds or a couple of minutes, but how many methods are there? We can find this out using dir() and a list comprehension.

``````# Create a list of method names that only contain all alphanumeric characters using isalpha()
c = dir(ab)
ls = [c[x] for x in range(len(c)) if c[x].isalpha()]
print(len(ls))

# Output
44
``````
• If you need a refresher on list comprehension, slicing, and associated list methods, take a quick look at my short post about them here.

## There are 44 possible string methods.

With 44 methods for each string object, you can be confident that there is a solution to your string related problem using one or chaining many methods to get your desired result. Here are some of the more common ones I use.

``````# Create test string
c = s[35:46]
c

# Output
'question \n'

c = c.rjust(30)
c = c.ljust(10)

# Output
'                    question \n'
'                    question \n          '

# Removing whitespace using rstrip() and lstrip() then both sides with strip()
c.rstrip()
c.lstrip()
c.strip()

# Output
'                    question'
'question \n          '
'question'

# Changing letter case with upper(), lower(), title(), and swapcase()
d = c.upper()
e = d.lower()
f = e.title()
g = f.swapcase()
ls2 = [d, e, f, g]
print(*ls2) # The "*" unpacks all values for printing

# Output
QUESTION
question
Question
qUESTION

# Using replace() to change instances of "ion" with nothing, this is case sensitive
ls3 = [x.replace("ion", "") for x in ls2]
print(*ls3)

# Output
QUESTION
quest
Quest
qUESTION

# Chaining string methods without escaping
d.rjust(10, "=").ljust(12, "=").lower().replace("ion", " for the holy grail").replace(" ", "*").title().rjust(29, "|").rjust(33, "/").rjust(34, "0").ljust(35, ">")

# Output
'0////|==Quest*For*The*Holy*Grail==>'
# Chaining string methods together with escaping
d.rjust(10, "=")\
.ljust(12, "=")\
.lower()\
.replace("ion", " for the holy grail")\
.replace(" ", "*")\
.title()\
.rjust(29, "|")\
.rjust(33, "/")\
.rjust(34, "0")\
.ljust(35, ">")
# Output
'0////|==Quest*For*The*Holy*Grail==>'
``````

### A note on chaining methods ⚔️

Chaining string methods can be incredibly useful but tend to reduce the readability of your code. Remember, when chaining string methods together that the order of operations starts from the first method call and operates from left to right. Using the `\` lets you create a new line for your called methods and significantly increases readability at the cost of additional lines of code. I think escaping with `\` is a lot easier to follow and read. The choice is yours which style you use and both will produce the same results.

In my example of chaining, the order of operations would be:

• `rjust(10, "=") -> ‘==QUESTION’`

• `ljust(12, "=") -> ‘==QUESTION==’`

• `lower() -> ‘==question==’`

• `replace(“ion”, “ for the holy grail”) -> ‘==quest for the holy grail==’`

• `replace(“ ”, “*”) -> ‘==quest*for*the*holy*grail==’`

• `title() -> '===Quest*For*The*Holy*Grail==’`

• `rjust(29, “|”) -> ‘|==Quest*For*The*Holy*Grail==’`

• `rjust(33, “/”) -> ‘////|==Quest*For*The*Holy*Grail==’`

• `rjust(34, “0”) -> ‘0////|==Quest*For*The*Holy*Grail==’`

• `ljust(35, “>”) -> ‘0////|==Quest*For*The*Holy*Grail==>’`

## String Interpolation

String interpolation lets you replace placeholders in a given string with the value of a variable(s). Here are 𝟑 ways of interpolating Python strings:

``````first = "Monty"
last = "Python"

# % operator
print("Hello %s %s" % (first, last))
print("Hello %s %s" % (first.upper(), last.swapcase()))

# Ouput
Hello Monty Python
Hello MONTY pYTHON

# format
print("Look over there {}!".format(first))
print("Look over there {}!".format([x.upper() for x in first]))

# Output
Look over there Monty!
Look over there ['M', 'O', 'N', 'T', 'Y']!

# f-strings
print(f"We meet at last Mr.{last}, {('Mua'+'Haha'*2)}!")

# Output
We meet at last Mr.Python, MuaHahaHaha!
``````

As you can see we can perform string manipulations while formatting. Manipulating your string and formating them simultaneously will decrease readability, but for some cases, it might be ok to use quick string manipulation to get your desired output. Try out your own manipulations with string interpolation and see what creative instances you can come up with!

## Onwards and Upwards

Now that you have a good understanding of string objects in Python, you have to use what you’ve learned. Choose your favorite quote and manipulate it to your liking.

Making sure to physically practice is the most important part of coding and it has dramatically helped me become a better programmer by committing some time every day.

Find the code for the blog here!

Please feel free to leave any feedback,. I’m always trying to improve and appreciate learning from my own mistakes. Thanks for reading!