Python String Methods Complete List

Python provides an extensive collection of built-in string methods that allow for efficient manipulation and processing of strings. In Python, a string is classified as an immutable data type, which means that all of these methods generate a new string while leaving the original string unaltered.

Python String Methods to Change Case

The 'str' class in Python provides a variety of methods for altering the case of characters within a string. Below is a table outlining these different methods:

S. No. String Method Description
1 str.upper() This method converts all characters in the string to uppercase.
2 str.lower() This method converts all characters in the string to lowercase.
3 str.title() This method capitalizes the first letter of each word.
4 str.capitalize() This method capitalizes only the first letter of the string.
5 str.swapcase() This method swaps the uppercase letters in the string to the lowercase; and vice versa.

Let us see an example showing the implementation of these string methods in Python.

Example

Example

# showing the use of different python string methods to change case

str_1 = str.upper("i love learning python")   # using upper() method

str_2 = str.lower("PYTHON IS FUN WITH HELLO WORLD") # using lower() method

str_3 = str.title("welcome to logicpractice tech")   # using title() method

str_4 = str.capitalize("welcome to logicpractice tech")  # using capitalize() method

str_5 = str.swapcase("Learning Python Feels Wonderful")  # using swapcase() method

# printing the results

print(str_1)

print(str_2)

print(str_3)

print(str_4)

print(str_5)

Output:

Output

I LOVE LEARNING PYTHON

python is fun with logicpractice tech

Welcome To Example

Welcome to logicpractice tech

lEARNING pYTHON fEELS wONDERFUL

Explanation:

In the preceding illustration, we have employed various string functions, including upper, lower, title, capitalize, and swapcase, to modify the casing of the designated strings in Python.

Python String Methods to Search and Find Substrings

The 'str' class in Python provides numerous methods for finding substrings within strings. The table below outlines the various methods available:

S. No. String Method Description
1 str.find(substring) This method is used to return the index of the first occurrence of substring, or -1 if not found.
2 str.index(substring) This method is similar to the find() method; however it raises an error if substring is not found.
3 str.rfind(substring) This method is used to return the highest index of substring, or -1 if not found.
4 str.rindex(substring) This method is similar to the rfind() method; however it raises an error if substring is not found.
5 str.count(substring) This method counts the number of occurrences of substring.
6 str.startswith(prefix) This method is used for checking if the string starts with prefix.
7 str.endswith(suffix) This method is used to check if the string ends with suffix.

Let us see an example showing the implementation of these string methods in Python.

Example

Example

# showing the use of different python string methods to search and find substrings

text = """

Learning Python is fun with us.

C# Tutorial offers a simple interface where students

can have effortless experience while learning programming from basics.

With its "Execute Now" feature, you can test your code

without installing Python in your system.

I love learning Python!

"""

index = text.find("Example")       # using find() method

print(f"Index of 'Example': {index}")

index = text.rfind("Example")      # using rfind() method

print(f"Last index of 'Example': {index}")

try:

    index = text.index("students")    # using index() method

    print(f"Index of 'students': {index}")

except ValueError:

    print("Substring 'students' not found.")

try:

    index = text.rindex("learning")   # using rindex() method

    print(f"Last index of 'learning': {index}")

except ValueError:

    print("Substring 'learning' not found.")

starts_with_logicpractice = text.startswith("Example") # using startswith() method

print(f"Starts with 'Example': {starts_with_logicpractice}")

ends_with_basics = text.endswith("basics.")   # using endswith() method

print(f"Ends with 'basics.': {ends_with_basics}")

count_logicpractice = text.count("Example")     # using count() method

print(f"Count of 'Example': {count_logicpractice}")

Output:

Output

Index of 'Example': 29

Last index of 'Example': 42

Index of 'students': 86

Last index of 'learning': 273

Starts with 'Example': False

Ends with 'basics.': False

Count of 'Example': 2

Explanation:

In the preceding illustration, we have employed various string methods such as find, rfind, index, rindex, count, startswith, and endswith to identify the positions of the substrings within the specified string.

Python String Methods to Split and Join Strings

The 'str' class in Python provides various methods that assist in splitting and concatenating strings. The following table presents a compilation of these methods:

S. No. String Method Description
1 str.split(sep) This method is used to split the string by sep into a list
2 str.rsplit(sep, maxsplit) This method is used to split from the right side
3 str.partition(sep) This method is used to split into three parts: before, sep, and after
4 str.join(iterable) This method is used to join elements of an iterable with str as a separator

Let us see an example showing the implementation of these string methods in Python.

Example

Example

# showing the use of different python string methods to split and join strings

# Splitting strings

text = "Learning Python is fun with us."

# splitting the text by spaces

split_str = text.split()

print("Split string:", split_str)

# splitting the text by spaces, but only at the last two occurrences

rsplit_str = text.rsplit(' ', 2)

print("Right split string:", rsplit_str)

# partitioning the text at the first occurrence of "sample"

partition_str = text.partition("sample")

print("Partitioned string:", partition_str)

# joining strings

list_of_str = ["Example", "Tech", "offers", "best", "tutorials", "to", "learn", "Python"]

# joining the list of strings with spaces

joined_str = " ".join(list_of_str)

print("Joined string:", joined_str)

# joining the list of strings with a comma and space

joined_str_comma = ", ".join(list_of_str)

print("Joined string with comma:", joined_str_comma)

Output:

Output

Split string: ['Learning', 'Python', 'is', 'fun', 'with', 'Example', 'Tech.']

Right split string: ['Learning Python is fun with', 'Example', 'Tech.']

Partitioned string: ('Learning Python is fun with us.', '', '')

Joined string: C# Tutorial offers best tutorials to learn Python

Joined string with comma: C# Tutorial, Tech, offers, best, tutorials, to, learn, Python

Explanation:

In the preceding illustration, various string functions such as split, rsplit, partition, and join have been employed to separate and concatenate the specified string.

Python String Methods to Validate Strings

The 'str' class in Python provides various methods that enable us to verify if a string is composed solely of particular categories of characters. The following table presents these methods:

S. No. String Method Description
1 str.isalpha() This method is used to return True if all characters are alphabetic
2 str.isdigit() This method is used to return True if all characters are digits
3 str.isalnum() This method is used to return True if all characters are alphanumeric
4 str.isspace() This method is used to return True if all characters are spaces
5 str.islower() This method is used to return True if all characters are lowercase
6 str.isupper() This method is used to return True if all characters are uppercase
7 str.istitle() This method is used to return True if the string is in title case

Let us see an example showing the implementation of these string methods in Python.

Example

Example

# showing the use of different python string methods to validate string

# a function to validate the string

def validate_string(input_str):

  """Validates a string using various string methods."""

  # printing the results

  print(f"Given String: {input_str}")

  print(f"Is alphabetic (str.isalpha()): {input_str.isalpha()}")

  print(f"Is digit (str.isdigit()): {input_str.isdigit()}")

  print(f"Is alphanumeric (str.isalnum()): {input_str.isalnum()}")

  print(f"Is space (str.isspace()): {input_str.isspace()}")

  print(f"Is lowercase (str.islower()): {input_str.islower()}")

  print(f"Is uppercase (str.isupper()): {input_str.isupper()}")

  print(f"Is titlecase (str.istitle()): {input_str.istitle()}")

  print("-" * 30)

# main function

if __name__ == "__main__":

  # calling the function to validate the string

  validate_string("Welcome")

  validate_string("PYTHON")

  validate_string("Example")

  validate_string(" ")

  validate_string("hello friends")

Output:

Output

Given String: Welcome

Is alphabetic (str.isalpha()): True

Is digit (str.isdigit()): False

Is alphanumeric (str.isalnum()): True

Is space (str.isspace()): False

Is lowercase (str.islower()): False

Is uppercase (str.isupper()): False

Is titlecase (str.istitle()): True

------------------------------

Given String: PYTHON

Is alphabetic (str.isalpha()): True

Is digit (str.isdigit()): False

Is alphanumeric (str.isalnum()): True

Is space (str.isspace()): False

Is lowercase (str.islower()): False

Is uppercase (str.isupper()): True

Is titlecase (str.istitle()): False

------------------------------

Given String: C# Tutorial

Is alphabetic (str.isalpha()): False

Is digit (str.isdigit()): False

Is alphanumeric (str.isalnum()): False

Is space (str.isspace()): False

Is lowercase (str.islower()): False

Is uppercase (str.isupper()): False

Is titlecase (str.istitle()): True

------------------------------

Given String:

Is alphabetic (str.isalpha()): False

Is digit (str.isdigit()): False

Is alphanumeric (str.isalnum()): False

Is space (str.isspace()): True

Is lowercase (str.islower()): False

Is uppercase (str.isupper()): False

Is titlecase (str.istitle()): False

------------------------------

Given String: hello friends

Is alphabetic (str.isalpha()): False

Is digit (str.isdigit()): False

Is alphanumeric (str.isalnum()): False

Is space (str.isspace()): False

Is lowercase (str.islower()): True

Is uppercase (str.isupper()): False

Is titlecase (str.istitle()): False

------------------------------

Explanation:

In the preceding example, a function has been created to check the validity of a specified string. Within this function, various string methods such as isalpha, isdigit, isalnum, isspace, islower, isupper, and istitle have been employed to assess the string's characteristics. The results of these methods have been evaluated against multiple examples.

Python String Methods for String Alignment and Formatting

The 'str' class in Python provides various methods for formatting strings for presentation. Below is a table that illustrates the quantity of string methods accessible for string formatting:

S. No. String Method Description
1 str.center(width, fillchar) This method is used to center the string with padding.
2 str.ljust(width, fillchar) This method is used to align the string to the left with padding.
3 str.rjust(width, fillchar) This method is used to align the string to the right with padding.
4 str.zfill(width) This method is used to pad the string with zeros.
5 str.format() This method is used to format a string dynamically.
6 f"{var}" This method is used to provide f-string formatting.

Let us see an example showing the implementation of these string methods in Python.

Example

Example

# showing the use of different python string methods for string alignment and formatting

# Using ljust(), rjust(), and center() for alignment

text = "Example"

print(text.ljust(10, '-'))  # Left-align with '-' padding

print(text.rjust(10, '-'))  # Right-align with '-' padding

print(text.center(10, '-')) # Center-align with '-' padding

# Using format() for string formatting with alignment

name = "Vicky"

age = 29

print("My name is {:10} and I am {:3} years old.".format(name, age)) # Aligned with specified width

# Using f-strings (formatted string literals) for alignment

print(f"My name is {name:10} and I am {age:3} years old.")

# Using zfill() for zero padding

number = "1243"

print(number.zfill(5))  # Pad with zeros to make it 5 characters long

# Using format() with alignment specifiers for decimal places

pi = 3.14159

print("{:.2f}".format(pi)) # Format with 2 decimal places

print("{:08.2f}".format(pi)) # Format with 2 decimal places and zero-padding up to 8 characters

# Example of alignment with custom formatting

string = "Example"

print(f"{string:^15}")  # Center align the string within 15 characters

print(f"{string:<15}")  # Left align the string within 15 characters

print(f"{string:>15}")  # Right align the string within 15 characters

Output:

Output

C# Tutorial----

----C# Tutorial

--C# Tutorial--

My name is Morgan     and I am  29 years old.

My name is Morgan     and I am  29 years old.

01243

3.14

00003.14

    C# Tutorial

C# Tutorial

         C# Tutorial

Explanation:

In the example provided, various string manipulation techniques have been employed, including ljust, rjust, center, zfill, format, and f-string, to achieve alignment and formatting of the string.

Python String Methods for String Encoding and Decoding

The 'str' class in Python provides various methods for transforming strings into multiple encodings. The table below illustrates the total number of string methods that can be utilized for encoding and decoding purposes:

S. No. String Method Description
1 str.encode(encoding) Converts string to bytes using encoding
2 bytes.decode(encoding) Converts bytes back to string

Let us see an example showing the implementation of these string methods in Python.

Example

Example

# showing the use of different python string methods for string encoding and decoding

# Example of encoding and decoding using UTF-8

text = "This is a sample text string with special characters like éàçüö."

# encoding the string to bytes using UTF-8

encoded_text = text.encode('utf-8')

print(f"Encoded text: {encoded_text}")

# decoding the bytes back to a string using UTF-8

decoded_text = encoded_text.decode('utf-8')

print(f"Decoded text: {decoded_text}")

# Example of encoding and decoding using ASCII

# Note: ASCII only supports a limited set of characters

try:

  text.encode('ascii')

except UnicodeEncodeError:

  print("The string contains characters that cannot be encoded using ASCII.")

# Example of using base64 encoding and decoding

import base64

# encoding the string to base64

encoded_base64 = base64.b64encode(text.encode('utf-8'))

print(f"Base64 encoded text: {encoded_base64}")

# decoding the base64 encoded string

decoded_base64 = base64.b64decode(encoded_base64).decode('utf-8')

print(f"Base64 decoded text: {decoded_base64}")

Output:

Output

Encoded text: b'This is a sample text string with special characters like \xc3\xa9\xc3\xa0\xc3\xa7\xc3\xbc\xc3\xb6.'

Decoded text: This is a sample text string with special characters like éàçüö.

The string contains characters that cannot be encoded using ASCII.

Base64 encoded text: b'VGhpcyBpcyBhIHNhbXBsZSB0ZXh0IHN0cmluZyB3aXRoIHNwZWNpYWwgY2hhcmFjdGVycyBsaWtlIMOpw6DDp8O8w7Yu'

Base64 decoded text: This is a sample text string with special characters like éàçüö.

Explanation:

In the preceding example, we have demonstrated how to utilize the encode and decode methods to convert the specified text string into various encodings (such as UTF-8, ASCII, and Base64) and subsequently decode those encodings.

Complete List of String Methods in Python

Below is the comprehensive compilation of String Methods that Python offers, allowing developers to manipulate Strings effectively.

S. No. String Method Description
1 capitalize() This method converts the first character to uppercase.
2 casefold() This method converts the string to lowercase (more aggressive than lower()).
3 center(width, fillchar) This method centers the string with the given width and optional fill character.
4 count(substring, start, end) This method counts occurrences of a substring in the string.
5 encode(encoding, errors) This method returns an encoded version of the string.
6 endswith(suffix, start, end) This method checks if the string ends with the given suffix.
7 expandtabs(tabsize) This method replaces tab characters (\t) with spaces.
8 find(substring, start, end) This method returns the index of the first occurrence of the substring (or -1 if not found).
9 format(args, *kwargs) This method formats the string with given arguments.
10 format_map(mapping) This method formats the string using a dictionary mapping.
11 index(substring, start, end) This method is like find(), but raises a ValueError if the substring is not found.
12 isalnum() This method checks if all characters are alphanumeric.
13 isalpha() This method checks if all characters are alphabetic.
14 isascii() This method checks if all characters are ASCII.
15 isdecimal() This method checks if all characters are decimals.
16 isdigit() This method checks if all characters are digits.
17 isidentifier() This method checks if the string is a valid Python identifier.
18 islower() This method checks if all characters are lowercase.
19 isnumeric() This method checks if all characters are numeric.
20 isprintable() This method checks if all characters are printable.
21 isspace() This method checks if the string contains only whitespace.
22 istitle() This method checks if the string follows the title case.
23 isupper() This method checks if all characters are uppercase.
24 join(iterable) This method joins elements of an iterable with the string as a separator.
25 ljust(width, fillchar) This method left-justifies the string within a given width.
26 lower() This method converts all characters to lowercase.
27 lstrip(chars) This method removes leading whitespace or specified characters.
28 maketrans(x, y, z) This method creates a translation table for translate().
29 partition(separator) This method splits the string into a tuple (before separator, separator, after separator).
30 removeprefix(prefix) This method removes the specified prefix from the string.
31 removesuffix(suffix) This method removes the specified suffix from the string.
32 replace(old, new, count) This method replaces the occurrences of old with new.
33 rfind(substring, start, end) This method finds the last occurrence of a substring.
34 rindex(substring, start, end) This method is like rfind(), but raises a ValueError if not found.
35 rjust(width, fillchar) This method right-justifies the string within a given width.
36 rpartition(separator) This method splits the string into a tuple from the right.
37 rsplit(separator, maxsplit) This method splits the string from the right.
38 rstrip(chars) This method removes trailing whitespace or specified characters.
39 split(separator, maxsplit) This method splits the string into a list.
40 splitlines(keepends) This method splits the string at line breaks.
41 startswith(prefix, start, end) This method checks if the string starts with the given prefix.
42 strip(chars) This method removes both leading and trailing whitespace or specified characters.
43 swapcase() This method swaps uppercase characters to lowercase and vice versa.
44 title() This method converts the first character of each word to uppercase.
45 translate(table) This method translates the string using a given translation table.
46 upper() This method converts all characters to uppercase.
47 zfill(width) This method pads the string with zeros on the left.

Conclusion

In this guide, we have explored the different String Methods that Python offers for the manipulation of Strings.

Python String Methods - FAQs

1. How can we check if a string contains a specific substring?

Python provides the find method, which allows users to determine whether a substring exists within a string.

Example

Example

greetings = "Welcome to our tutorial"

print(greetings.find("Example"))

print(greetings.find("Python"))

Output:

Output

11

-1

The find method provides the index of the initial occurrence of a specified substring. If the substring does not exist within the string, it will return -1.

2. How do we replace a word or character in a string?

In Python, the replace function is available to change a specific character or word to a different one.

Example

Example

greetings = "Welcome to our tutorial"

new_greetings = greetings.replace("Welcome to", "Learn with")

print(new_greetings)

Output:

Output

Learn with us

The method replace(old, new) substitutes every instance of old with new. Given that strings in Python are immutable, the replace function produces a new string rather than altering the existing one.

3. How do we split a string into a list of words?

Python includes the split function, which allows you to break a string into a list by using a designated delimiter (with the default being a space).

Example

Example

fruits = "apple banana mango"

list_of_fruits = fruits.split()

print(list_of_fruits)

Output:

Output

['apple', 'banana', 'mango']

In the absence of an argument, the function separates the input based on whitespace. When a designated delimiter is specified, it performs the split operation based on that delimiter:

Example

Example

csv_data = "Tom,Holland,55,New York"

data_list = csv_data.split(",")

print(data_list)

Output:

Output

['Tom', 'Holland', '55', 'New York']

4. How can we check if a string starts or ends with a specific substring?

You can use startswith and endswith methods.

Example

Example

greetings = "Welcome to our tutorial"

# Check if it starts with "Wel"

print(greetings.startswith("Wel"))

# Check if it ends with "ech"

print(greetings.endswith("ech"))

Output:

Output

True

True

These functions yield True if the string either begins or concludes with the designated substring; otherwise, they return False. This functionality is beneficial for verifying file formats, URLs, and similar applications.

5. How do we convert a string to uppercase or lowercase?

Python offers the methods upper, lower, and title for the purpose of changing the case of strings.

Example

Example

greetings = "Welcome to our tutorial"

print(greetings.upper())  # Converts to uppercase

print(greetings.lower())  # Converts to lowercase

print(greetings.title())  # Capitalizes first letter of each word

Output:

Output

WELCOME TO HELLO WORLD

welcome to logicpractice tech

Welcome To Example

Input Required

This code uses input(). Please provide values below: