In this tutorial, you'll write Python programs to solve frequently asked questions on string operations.

You'll learn how to check if Python strings are palindromes, anagrams, and are in the title case.

Python Strings: A Quick Review

In Python, strings are powerful built-in data types. They can store a sequence of characters.

Indexing in Python Strings: Like all Python iterables, strings are also zero-indexed. So the valid indices for a string of length N are 0, 1, 2 up to N – 1.

python-strings

Python also supports negative indexing to access elements from the end of the string. So -1 is the index of the last character in the string, -2 is the index of the second-to-last character in the string, and so on.

Immutability of Python Strings: In addition, strings in Python are immutable, so you cannot modify them in place. However, you can call several string methods on them and obtain copies of strings with the desired result.

Now that we've reviewed the basics of Python strings, let's proceed to solve some simple yet interesting problems.

Let's start.

Check if a Python String is a Palindrome

Problem: Given a Python string, check whether or not it's a palindrome.

If yes, return True; else, return False.

So our first problem is to check whether or not a given string is a palindrome.

A palindrome is a string that reads the same from left to right as well as from right to left. Let's list down a few examples: racecar, refer, level, madam, radar, and so on.

python-string-palindrome

Here are the steps to solve this problem:

  • Obtain a reversed copy of the string and store it in another variable, if needed.
  • Compare the values of the original string and the reversed string.
  • If they are equal, the string is a palindrome. So return True, and stop.
  • If the original and reversed copies are not equal, the string is not a palindrome. So we should return False.

The key operation is to obtain a reversed copy of the string. In Python, there are a few different ways you can do this.

However, we will go over two approaches:

  • Using string slicing
  • Using the reversed() function and the join() method

How to Reverse a Python String Using Slicing

The syntax <any_str>[start: stop: step] returns a slice of the string <any_str> from start up to but not including stop, with step size step.

  • If you omit start, the slice starts at the beginning of the string.
  • If you don't specify the stop index, the slice extends up to the end of the string.
  • And negative values of step can be used to return slices starting from the end of the string.

So <any_str>[::-1] returns a reversed copy of the string.

The following code cell contains the definition of the function is_palindrome().

It takes in a string as the argument, and returns True or False depending on whether or not it's a palindrome.

Here, we've used string slicing to obtain a reverse copy of the string.

def is_palindrome(this_str):
  rev_str = this_str[::-1]
  if (this_str == rev_str):
    return True
  else:
    return False

▶️ Now that we've defined the function, we can go ahead and call with any valid string as the argument.

is_palindrome("racecar")
True

In the above code cell, racecar is a palindrome. So the function is_palindrome() returns True as expected.

Now, try calling the function with any string that is not a palindrome, such as river.

is_palindrome("river")
False

And as you can see, it returns False, which is correct. ✅

How to Reverse a Python String Using reversed() and join()

In Python, you can use the join() method along with the reversed() function to reverse a string.

  • The reversed() function returns a reverse iterator through the characters in the string.
  • The join() method can then be used to join those characters in the reverse order.

Using the above method, you can rewrite the is_palindrome() function as in the code cell below.

def is_palindrome(this_str):
  rev_str = ''.join(reversed(this_str))
  if (this_str == rev_str):
    return True
  else:
    return False

You can also use the is_palindrome() function inside list comprehension to collect all palindromes from a longer list of strings.

str_list = ["refer","blue","level","12321","dragon"]

palindromes = [string for string in str_list if is_palindrome(string)]
print(palindromes)
# Output
['refer', 'level', '12321']

Here's how the above code works:

  • Traverse through str_list, call is_palindrome() on each string.
  • If is_palindrome() returns True, add the string to the palindromes list.

As you can see in the output above, palindromes is a list of all palindromic strings in str_list.

Check if Two Python Strings are Anagrams

Another popular question that you may come across in interviews is to check whether or not a pair of strings str1 and str2 are anagrams.

Two strings are said to be anagrams if the counts of the characters in the two strings are exactly the same. This means that you can obtain one of the strings by permuting or rearranging the characters in the other string.

Examples of anagrams include state-taste, save-vase, elbow-below, and so on.

python-strings-anagrams

How to Check for Anagrams Using Counter Object in Python

A simple and intuitive way is to compute the number of occurrences of each character in the two strings. And then check if the counts are equal.

This can be done all the more easily using the Counter object from the itertools module. The Counter object returns a Python dictionary: with the characters as the keys and the corresponding counts as the values.

Consider the strings "save" and "vase" as shown below.

str1 = "save"
str2 = "vase"

Here, c1 and c2 are counter objects containing the character counts of the strings str1 and str2 respectively.

from collections import Counter
c1 = Counter(str1)
c2 = Counter(str2)
print(c1)
print(c2)
c1 == c2

# Output
Counter({'s': 1, 'a': 1, 'v': 1, 'e': 1})
Counter({'v': 1, 'a': 1, 's': 1, 'e': 1})
True

c1 == c2 returns True as str1 and str2 are anagrams.

Using this logic, we can now go ahead and define the function are_anagrams() with two parameters word1 and word2. In the function body, we check if Counter(word1) == Counter(word2).

def are_anagrams(word1, word2):
  if Counter(word1) ==  Counter(word2):
    return True
  else:
    return False

▶️ To verify, call are_anagrams() with str1, str2 as the arguments. As str1 and str2 are anagrams (“save” and “vase”), the function returns True, which is correct.

are_anagrams(str1, str2)
True

How to Check for Anagrams Using Sorted Copies of Strings

There is another way you can do this.

If two strings are anagrams, then their sorted copies are equal.

So we can rewrite the function are_anagrams() to check if the sorted version of str1 is the same as the sorted copy of str2. If they are equal, then the two strings are anagrams; else, they are not.

Using the above method to check equality of sorted copies, we can rewrite the function are_anagrams() as follows.

def are_anagrams(word1, word2):
  if sorted(word1) ==  sorted(word2):
    return True
  else:
    return False

Let us now make a few function calls.

  • The strings “elbow” and “below” are anagrams and the function are_anagrams() returns True.
  • And “state” and “tasted” are not anagrams, and the function returns False.
are_anagrams("below","elbow")
True

are_anagrams("state","tasted")
False

Check if a Python String is in Title Case

Here's our final question for this tutorial.

Problem: Given a string: a person's name—with first name and last name.

You have to check if the first letter of both the first and last names are capitalized.

This type of casing where the first letter of each word is capitalized is called title case.

So you've to check if the name is in title case:

1. If yes, output a message that the formatting is in title case.

2. Else, return a copy of the string formatted in the title case

python-string-title-case
  • Python has a built-in string method istitle(), which checks whether a string is in the title case.

<str>.istitle() returns True if the string <str> is formatted in the title case, else it returns False.

  • And Python's string method title() returns a copy of the string formatted in the title case.

So now you can use these two methods to solve the problem.

Define a function check_titlecase() that accepts name as the argument.

  • You can call the istitle() method on the input string to check if it is formatted in title case.
  • If True, you can print that the string is already in title case.
  • Else, you can call the title() method and return a copy of the string in the title case.

The following code cell shows the definition of the check_titlecase() function.

def check_titlecase(name):
  if name.istitle():
    print(f"'{name}' is already formatted in title case.")
  else:
    return name.title()

Let us now call the check_titlecase() method with an argument.

check_titlecase("jane smith")

# Output
Jane Smith

In the output above, you can see that the string “Jane Smith” is now in the title case.

▶️ Let us take another example.

check_titlecase("agatha Christie")

# Output
Agatha Christie

This time, let's call the function with a title-cased string.

check_titlecase("Grace Hopper")

# Output
'Grace Hopper' is already formatted in title case.

We get notified that the string is formatted in the title case, and the function works as expected.

Conclusion 👩‍🏫

Now let's summarize the problems we have discussed so far.

  • To check if a string is a palindrome, check if the string and its reversed version are equal. You may use string slicing or built-in methods to reverse strings.
  • To check if two strings are anagrams, check if their sorted copies are equal. And to sort a string, use the built-in sorted() function.
  • To verify if a name is in title case, use the .istitle() method for checking and the .title() method to obtain a title-cased copy of the string.

I hope you enjoyed this tutorial on Python strings. As a next step, learn how to use list comprehensions in Python or learn about the not equal operator in Python.

Happy learning and coding!🎉