Data types and variables
Operators
Modules and Packages
Conversion Programs
More Code Examples
Cheat Sheet

String Methods in Python

Python provides a rich set of methods for string manipulation. Here, we’ll explore some of the most commonly used string methods, including split(), join(), replace(), strip(), find(), upper(), lower(), startswith(), endswith(), and format().

split()

The split() method splits a string into a list of substrings based on a specified delimiter.

Syntax

str.split(separator=None, maxsplit=-1)
  • separator: The delimiter on which to split the string (default is any whitespace).
  • maxsplit: The maximum number of splits (default is -1, which means no limit).

Example

text = "Hello world, welcome to Python"
words = text.split()
print(words)  # ['Hello', 'world,', 'welcome', 'to', 'Python']

text = "apple,orange,banana,grape"
fruits = text.split(',')
print(fruits)  # ['apple', 'orange', 'banana', 'grape']

join()

The join() method concatenates a list of strings into a single string with a specified delimiter.

Syntax

separator.join(iterable)
  • separator: The string inserted between each string in the iterable.
  • iterable: A list or any iterable of strings.

Example

words = ['Hello', 'world', 'welcome', 'to', 'Python']
sentence = ' '.join(words)
print(sentence)  # Hello world welcome to Python

fruits = ['apple', 'orange', 'banana', 'grape']
fruit_string = ','.join(fruits)
print(fruit_string)  # apple,orange,banana,grape

replace()

The replace() method replaces occurrences of a substring within a string with another substring.

Syntax

str.replace(old, new, count=-1)
  • old: The substring to be replaced.
  • new: The substring to replace with.
  • count: The number of times to replace (default is all occurrences).

Example

text = "Hello world"
new_text = text.replace("world", "Python")
print(new_text)  # Hello Python

text = "banana banana banana"
new_text = text.replace("banana", "apple", 2)
print(new_text)  # apple apple banana

strip()

The strip() method removes leading and trailing whitespace (or specified characters) from a string.

Syntax

str.strip(chars=None)
  • chars: A string specifying the set of characters to be removed (default is whitespace).

Example

text = "   Hello world   "
stripped_text = text.strip()
print(stripped_text)  # "Hello world"

text = "xxHello worldxx"
stripped_text = text.strip('x')
print(stripped_text)  # "Hello world"

find()

The find() method searches for a substring within a string and returns the index of the first occurrence. It returns -1 if the substring is not found.

Syntax

str.find(sub, start=0, end=len(str))
  • sub: The substring to search for.
  • start: The starting index for the search (default is 0).
  • end: The ending index for the search (default is the end of the string).

Example

text = "Hello world"
index = text.find("world")
print(index)  # 6

index = text.find("Python")
print(index)  # -1

upper()

The upper() method converts all characters in a string to uppercase.

Syntax

str.upper()

Example

text = "Hello world"
upper_text = text.upper()
print(upper_text)  # HELLO WORLD

lower()

The lower() method converts all characters in a string to lowercase.

Syntax

str.lower()

Example

text = "Hello World"
lower_text = text.lower()
print(lower_text)  # hello world

startswith()

The startswith() method checks if a string starts with a specified substring.

Syntax

str.startswith(prefix, start=0, end=len(str))
  • prefix: The substring to check.
  • start: The starting index for the check (default is 0).
  • end: The ending index for the check (default is the end of the string).

Example

text = "Hello world"
print(text.startswith("Hello"))  # True
print(text.startswith("world"))  # False

endswith()

The endswith() method checks if a string ends with a specified substring.

Syntax

str.endswith(suffix, start=0, end=len(str))
  • suffix: The substring to check.
  • start: The starting index for the check (default is 0).
  • end: The ending index for the check (default is the end of the string).

Example

text = "Hello world"
print(text.endswith("world"))  # True
print(text.endswith("Hello"))  # False

format()

The format() method formats a string by replacing placeholders with specified values.

Syntax

str.format(*args, **kwargs)
  • *args: Positional arguments to replace placeholders.
  • **kwargs: Keyword arguments to replace placeholders.

Example

text = "Hello, {}. Welcome to {}."
formatted_text = text.format("Alice", "Python")
print(formatted_text)  # Hello, Alice. Welcome to Python.

text = "Hello, {name}. Welcome to {language}."
formatted_text = text.format(name="Alice", language="Python")
print(formatted_text)  # Hello, Alice. Welcome to Python.

Summary

  • split(): Splits a string into a list of substrings.
  • join(): Joins a list of strings into a single string with a delimiter.
  • replace(): Replaces occurrences of a substring with another substring.
  • strip(): Removes leading and trailing whitespace or specified characters.
  • find(): Finds the index of the first occurrence of a substring.
  • upper(): Converts all characters to uppercase.
  • lower(): Converts all characters to lowercase.
  • startswith(): Checks if a string starts with a specified substring.
  • endswith(): Checks if a string ends with a specified substring.
  • format(): Formats a string by replacing placeholders with specified values.