Python String Methods: In-Depth Guide to String Manipulation

Boost Efficiency in Python: Practical String Methods for Text Processing and Data

Python String Methods: In-Depth Guide to String Manipulation

What is a string?

A string is a built-in data structure and one of the most frequently used data type in python. Essentially, it is a sequence of characters surrounded by single quotation marks ('hello') or double quotation marks ("hello").

string = "123"
print(string)     
# 123

print(type(string))
# <class 'str'>

The point to be noted here is even though 123 is a number (int) but its type is shown as str. WHY? The answer is simple. Anything that is included in quotation marks is treated as string by the python interpreter.

Characteristics of strings

  • Strings are immutable in python. It means that once they are created, they cannot be changed.

  • Individual characters of strings can be accessed using indexing which starts from zero.

  • Multiline strings can be included using triple quotes (' ' ') or (" " ").

  • We can interact and manipulate strings by slicing, concatenation or various string methods available in python.

    Today, our focus will be on how to manipulate strings using string methods.

String methods

String methods can be directly used on string literals or on variables holding strings.

For example,

"hello".upper()
str1 = "hello"
str1.upper()

Following is the list of commonly used string methods to manipulate strings in python.

Note: All the outputs are written as comments.

  1. .upper()

    This method converts all characters to upper case.

     str1 = "hello"
     print(str1.upper())
    
     # HELLO
    
  2. .lower()

    Converts all characters to lower case.

     str1 = "HELLO"
     print(str1.lower())
    
     #hello
    
  3. .capitalize()

    Converts the first character of the string into capital letter and all the remaining characters to lowercase.

     str1 = "Hello World"
     print(str1.capitalize())
    
     # Hello world
    
  4. .title()

    Converts the first character of each word to uppercase and all the others to lowercase.

     str1 = "hello world"
     print(str1.title())
    
     # Hello World
    
  5. .replace(old, new)

    Replaces all occurrences of the specified(old) substring with the provided(new) substring.

     str1 = "hello world"
     print(str1.replace("world","python"))
    
     # hello python
    

    We can also provide an additional argument in this string method named count to specify how many occurrences we want to replace. By default, it replaces all occurrences.

     str1 = "hello world hello world hello world hello world"
     print(str1.replace("world","python",3))
    
     # hello python hello python hello python hello world
    
  6. .strip()

    It removes leading and trailing whitespaces (spaces, tabs, newlines) i.e. only from the start and end, not from the middle.

     str1 = "         hello        world         "
     print(str1.strip())
    
     # hello        world
    

    The strip method removes whitespaces by default, but it can also be used to remove characters by providing that specific character as argument of strip method.

     str1 = "level"
     print(str1.strip("l"))
     # eve
    
     str1 = "!!!! he!!o !!! wor!d  !!!"
     print(str1.strip("!"))
     #  he!!o !!! wor!d
    
  7. .lstrip()

    Removes the whitespaces or the specified character only from the left side.

     str1 = "!!!! he!!o !!! wor!d  !!!"
     print(str1.lstrip("!"))
    
     #  he!!o !!! wor!d  !!!
    
  8. .rstrip()

    Removes the whitespaces or the specified character only from the right side.

     str1 = "!!!! he!!o !!! wor!d  !!!"
     print(str1.rstrip("!"))
    
     #!!!! he!!o !!! wor!d
    
  9. .isalnum()

    Returns a Boolean value true if the string consists of only alphanumeric characters i.e. alphabets or numbers and returns false if any special characters are present in the string.

     str1 = "hello123"
     print(str1.isalnum())
     # True
    
     str1 = "hello@123"
     print(str1.isalnum())
     # False
    
  10. .swapcase()

    Swaps the case of all characters in the string i.e. uppercase letters to lowercase letters and lowercase letters to uppercase letters.

    str1="wELCOME TO nerd's BLOG"
    print(str1.swapcase())
    
    # Welcome to NERD'S blog
    

There are many more python string methods to explore, and we will do it in one of our upcoming posts. Till then practice these methods on your own and if you have any ambiguity let me know in comments.