The Wayback Machine - https://web.archive.org/web/20240809215229/https://www.geeksforgeeks.org/python-string-methods/
Open In App

Python String Methods

Last Updated : 25 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report

Python string methods is a collection of in-built Python functions that operates on lists.

Note: Every string method in Python does not change the original string instead returns a new string with the changed attributes. 

Python string is a sequence of Unicode characters that is enclosed in quotation marks. In this article, we will discuss the in-built string functions i.e. the functions provided by Python to operate on strings.

Case Changing of Python String Methods

The below Python functions are used to change the case of the strings. Let’s look at some Python string methods with examples:

  • lower(): Converts all uppercase characters in a string into lowercase
  • upper(): Converts all lowercase characters in a string into uppercase
  • title(): Convert string to title case
  • swapcase(): Swap the cases of all characters in a string
  • capitalize(): Convert the first character of a string to uppercase

Example: Changing the case of Python String Methods

Python
# Python3 program to show the
# working of upper() function
text = 'geeKs For geEkS'

# upper() function to convert
# string to upper case
print("\nConverted String:")
print(text.upper())

# lower() function to convert
# string to lower case
print("\nConverted String:")
print(text.lower())

# converts the first character to 
# upper case and rest to lower case 
print("\nConverted String:")
print(text.title())

# swaps the case of all characters in the string
# upper case character to lowercase and viceversa
print("\nConverted String:")
print(text.swapcase())

# convert the first character of a string to uppercase
print("\nConverted String:")
print(text.capitalize())

# original string never changes
print("\nOriginal String")
print(text)

Output
Converted String:
GEEKS FOR GEEKS

Converted String:
geeks for geeks

Converted String:
Geeks For Geeks

Converted String:
GEEkS fOR GEeKs

Original String
geeKs For geEkS

Time complexity: O(n) where n is the length of the string ‘text’
Auxiliary space: O(1)

List of String Methods in Python

Here is the list of in-built Python string methods, that you can use to perform actions on string:

Function Name Description
capitalize()Converts the first character of the string to a capital (uppercase) letter
casefold()Implements caseless string matching
center()Pad the string with the specified character.
count()Returns the number of occurrences of a substring in the string.
encode()Encodes strings with the specified encoded scheme
endswith()Returns “True” if a string ends with the given suffix
expandtabs()Specifies the amount of space to be substituted with the “\t” symbol in the string
find()Returns the lowest index of the substring if it is found
format()Formats the string for printing it to console
format_map()Formats specified values in a string using a dictionary
index()Returns the position of the first occurrence of a substring in a string
isalnum()Checks whether all the characters in a given string is alphanumeric or not
isalpha()Returns “True” if all characters in the string are alphabets
isdecimal()Returns true if all characters in a string are decimal
isdigit()Returns “True” if all characters in the string are digits
isidentifier()Check whether a string is a valid identifier or not
islower()Checks if all characters in the string are lowercase
isnumeric()Returns “True” if all characters in the string are numeric characters
isprintable()Returns “True” if all characters in the string are printable or the string is empty
isspace()Returns “True” if all characters in the string are whitespace characters
istitle()Returns “True” if the string is a title cased string
isupper()Checks if all characters in the string are uppercase
join()Returns a concatenated String
ljust()Left aligns the string according to the width specified
lower()Converts all uppercase characters in a string into lowercase
lstrip()Returns the string with leading characters removed
maketrans() Returns a translation table
partition()Splits the string at the first occurrence of the separator 
replace()Replaces all occurrences of a substring with another substring
rfind()Returns the highest index of the substring
rindex()Returns the highest index of the substring inside the string
rjust()Right aligns the string according to the width specified
rpartition()Split the given string into three parts
rsplit()Split the string from the right by the specified separator
rstrip()Removes trailing characters
splitlines()Split the lines at line boundaries
startswith()Returns “True” if a string starts with the given prefix
strip()Returns the string with both leading and trailing characters
swapcase()Converts all uppercase characters to lowercase and vice versa
title()Convert string to title case
translate()Modify string according to given translation mappings
upper()Converts all lowercase characters in a string into uppercase
zfill()Returns a copy of the string with ‘0’ characters padded to the left side of the string

Note: For more information about Python Strings, refer to Python String Tutorial.

Python String Methods – FAQs

What Are the Common String Methods in Python?

Python provides a variety of string methods for manipulating and working with strings. Some of the most common string methods include:

  • upper(): Converts all characters in a string to uppercase.
  • lower(): Converts all characters in a string to lowercase.
  • find(substring): Returns the lowest index in the string where the substring is found.
  • strip(): Removes any leading and trailing characters (space is the default).
  • replace(old, new): Replaces occurrences of a substring within the string.
  • split(delimiter): Splits the string at the specified delimiter and returns a list of substrings.
  • join(iterable): Concatenates elements of an iterable with a specified separator.
  • startswith(prefix): Checks if the string starts with the specified prefix.
  • endswith(suffix): Checks if the string ends with the specified suffix.

How to Find a Substring in Python?

To find a substring in a string, you can use the find() method. It returns the lowest index of the substring if it is found. If the substring is not found, it returns -1.

Example:

text = "Hello, World!"
index = text.find("World")
print(index) # Output: 7

# If the substring is not found
index = text.find("Python")
print(index) # Output: -1

How to Convert a String to Lower Case in Python?

You can convert all characters in a string to lowercase using the lower() method.

Example:

text = "Hello, World!"
lowercase_text = text.lower()
print(lowercase_text) # Output: hello, world!

What is the strip() Method Used for in Python?

The strip() method is used to remove leading and trailing characters from a string. By default, it removes whitespace, but you can specify a different character or set of characters to remove.

Example:

text = "   Hello, World!   "
stripped_text = text.strip()
print(stripped_text) # Output: "Hello, World!"

# Removing specific characters
text = "###Hello, World!###"
stripped_text = text.strip("#")
print(stripped_text) # Output: "Hello, World!"

How to Replace Characters in a String in Python?

To replace characters or substrings in a string, you can use the replace() method. It replaces all occurrences of the specified substring with another substring.

Example:

text = "Hello, World!"
replaced_text = text.replace("World", "Python")
print(replaced_text) # Output: Hello, Python!

# Replacing characters
text = "banana"
replaced_text = text.replace("a", "o")
print(replaced_text) # Output: bonono


Similar Reads

Python String Methods | Set 1 (find, rfind, startwith, endwith, islower, isupper, lower, upper, swapcase & title)
Some of the string basics have been covered in the below articles Strings Part-1 Strings Part-2 The important string methods will be discussed in this article1. find("string", beg, end) :- This function is used to find the position of the substring within a string.It takes 3 arguments, substring , starting index( by default 0) and ending index( by
4 min read
Python String Methods | Set 2 (len, count, center, ljust, rjust, isalpha, isalnum, isspace & join)
Some of the string methods are covered in the set 3 below String Methods Part- 1 More methods are discussed in this article 1. len() :- This function returns the length of the string. 2. count("string", beg, end) :- This function counts the occurrence of mentioned substring in whole string. This function takes 3 arguments, substring, beginning posi
4 min read
Python String Methods | Set 3 (strip, lstrip, rstrip, min, max, maketrans, translate, replace & expandtabs())
Some of the string methods are covered in the below sets.String Methods Part- 1 String Methods Part- 2More methods are discussed in this article1. strip():- This method is used to delete all the leading and trailing characters mentioned in its argument.2. lstrip():- This method is used to delete all the leading characters mentioned in its argument.
4 min read
Top 10 String methods in Pandas
Pandas is an open-source Python library that is mainly used for data manipulation and is widely popular in the fields of machine learning and data science. In this article, we will be learning various string methods that the Pandas library has got to offer. The Pandas library is very useful for the manipulation of strings as it provides us with var
4 min read
List Methods in Python | Set 1 (in, not in, len(), min(), max()...)
List methods are discussed in this article. 1. len() :- This function returns the length of list. List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1] print(len(List)) Output: 10 2. min() :- This function returns the minimum element of list. List = [2.3, 4.445, 3, 5.33, 1.054, 2.5] print(min(List)) Output: 1.054 3. max() :- This function returns the maximum eleme
2 min read
Accessing Attributes and Methods in Python
Attributes of a class are function objects that define corresponding methods of its instances. They are used to implement access controls of the classes. Attributes of a class can also be accessed using the following built-in methods and functions : getattr() - This function is used to access the attribute of object. hasattr() - This function is us
3 min read
Python | Float type and its methods
The float type in Python represents the floating point number. Float is used to represent real numbers and is written with a decimal point dividing the integer and fractional parts. For example, 97.98, 32.3+e18, -32.54e100 all are floating point numbers. Python float values are represented as 64-bit double-precision values. The maximum value any fl
3 min read
Bound, unbound, and static methods in Python
Methods in Python are like functions except that it is attached to an object.The methods are called on objects and it possibly make changes to that object. These methods can be Bound, Unbound or Static method. The static methods are one of the types of Unbound method. These types are explained in detail below. Bound methods If a function is an attr
5 min read
Http Request methods - Python requests
Python requests module has several built-in methods to make Http requests to specified URI using GET, POST, PUT, PATCH or HEAD requests. A Http request is meant to either retrieve data from a specified URI or to push data to a server. It works as a request-response protocol between a client and server. A web browser may be the client, and an applic
7 min read
Response Methods - Python requests
When one makes a request to a URI, it returns a response. This Response object in terms of python is returned by requests.method(), method being - get, post, put, etc. Response is a powerful object with lots of functions and attributes that assist in normalizing data or creating ideal portions of code. For example, response.status_code returns the
5 min read
Practice Tags :
three90RightbarBannerImg