Getting Started

Python - IntroductionPython - Hello World ProgramPython - SyntaxPython - Data TypesPython - Variables

Operators

Python - Arithmetic OperatorsPython - Relational OperatorsPython - Logical OperatorsPython - Assignment OperatorsPython - Bitwise OperatorsPython - Membership OperatorsPython - Identity OperatorsPython - Increment and Decrement Operators

Conditions

Python - If Else statement

Loop

Python - While LoopPython - For Loop

Numbers

Python - NumbersPython - Number Conversion

Strings

Python - StringsPython - String OperatorsPython - String FormattingPython - String MethodsPython - String Format Method

List

Python - ListPython - List Methods

Tuple

Python - Tuple

Set

Python - SetPython - Set Methods

Dictionary

Python - DictionaryPython - Dictionary Methods

Functions

Python - FunctionsPython - Functions - Variable length argumentsPython - Lambda Function

Scope of Variables

Python - Scope of Variables

Modules

Python - ModulesPython - Math ModulePython - JSON ModulePython - datetime ModulePython - time Module

I/O

Python - Read input from keyboard

File

Python - File Handling

Exception Handling

Python - Exception Handling

OOP

Python - Classes and ObjectsPython - Class Constructor __init__ methodPython - Class Destructor __del__ methodPython - Built-in Class AttributesPython - InheritancePython - Method OverridingPython - Method Overloading

Package Management

Python - PIP

Python - MySQL

Python - MySQL - Getting StartedPython - MySQL - Insert dataPython - MySQL - Select dataPython - MySQL - Update dataPython - MySQL - Delete data

Python - CSV

Python - Read data from CSV filePython - Write data in CSV file

Python - String Methods

Python

python logo

In this tutorial we will learn about string methods in Python.

Python provides us some built in string methods which we developers can use to modify and work with strings.

Here are some of the commonly used Python string methods with example.

capitalize

This method will capitalize the first letter of the string i.e., coverting lower case letter to upper case.

In the following example we are using capitalize() method to convert the given string.

# string
str = 'hello world'

# covert
result = str.capitalize()

# output
print(result)

We will get the following output.

Hello world

find

This method will find needle in a given haystack string or substring of a given haystack string.

Syntax

haystack.find(needle, start, end)

Where, start and end are optional. If start is set then we begin the search from the start index. If end is set then we search till that index but not including end index.

It returns an index if needle is found in the given haystack string or substring of the given haystack string.

It returns -1 if needle is not found.

In the following example we are using find() method to find "row" in the given string.

# string
needle = "row"
haystack = "The quick brown fox jumps over the lazy dog."

# find
print(haystack.find(needle))                        # 11
print(haystack.find(needle, 15))                    # -1
print(haystack.find(needle, 0, 15))                 # 11
print(haystack.find(needle, 10, len(haystack)))     # 11

In the first example we are checking if needle is present in the haystack string.

In the second example we are searching from index 15 onward in the haystack.

In the third example we are searching from index 0 till 15.

In the fourth example we are search from index 10 till the end of the haystack.

index

This method is similar to find method and will search for the needle in a given haystack string or substring of a given haystack string.

Syntax

haystack.index(needle, start, end)

Where, start and end are optional. If start is set then we begin the search from the start index. If end is set then we search till that index but not including end index.

It returns an index if needle is found in the given haystack string or substring of the given haystack string.

It raises an exception if the needle is not found.

len

This method will return the total number of characters in the given string.

In the following example we are using len() method to find the total number of characters in the string.

# string
str = 'HELLO WORLD'

# compute
result = len(str)

# output
print(result)          # 11

lower

This method will convert the given string into lower case.

In the following example we are using lower() method to convert the given string.

# string
str = 'HELLO WORLD'

# covert
result = str.lower()

# output
print(result)          # hello world

lstrip

This method is used to remove whitespaces from the left side of the string.

# string
str = '      HELLO WORLD'

# compute
result = str.lstrip()

# output
print(result)          # HELLO WORLD

We can also remove specific characters.

# string
str = '>>>>>>HELLO WORLD'

# compute
result = str.lstrip('>')

# output
print(result)          # HELLO WORLD

rstrip

This method is used to remove whitespaces from the right side of the string.

# string
str = 'HELLO WORLD      '

# compute
result = str.rstrip()

# output
print(result)          # HELLO WORLD

We can also remove specific characters.

# string
str = 'HELLO WORLD--------'

# compute
result = str.rstrip('-')

# output
print(result)          # HELLO WORLD

strip

This method is used to remove whitespaces from the both sides of the string.

# string
str = '    HELLO WORLD      '

# compute
result = str.strip()

# output
print(result)          # HELLO WORLD

We can also remove specific characters.

# string
str = '-------HELLO WORLD--------'

# compute
result = str.strip('-')

# output
print(result)          # HELLO WORLD

swapcase

This method will swap the case in the given string.

In the following example we are using swapcase() method to swap the case in the given string.

# string
str = 'Hello World 123'

# covert
result = str.swapcase()

# output
print(result)          # hELLO wORLD 123

upper

This method will convert the given string into upper case.

In the following example we are using upper() method to convert the given string.

# string
str = 'hello world 123'

# covert
result = str.upper()

# output
print(result)          # HELLO WORLD 123

Checking string

Following are some of the string methods that we can use to check the characters of the given string.

isalnum

This method will return True if all the characters in the given string is alphanumeric characters (lower case, upper case letters or digit), False otherwise.

In the following example we are using isalnum() method to check if the given string contains only alphnumeric characters.

# example 1
str = 'yusufshakeel'
print(str.isalnum())         # True

# example 2
str = '2018'
print(str.isalnum())         # True

# example 3
str = 'hello2018'
print(str.isalnum())         # True

# example 4
str = 'Yusuf Shakeel'
print(str.isalnum())         # False

# example 5
str = 'year-2018'
print(str.isalnum())         # False

Example 4 and 5 gives False as they contain at least one non-alphanumeric character.

isalpha

This method will return True if all the characters in the given string is alphabet characters (lower case and upper case letters), False otherwise.

In the following example we are using isalpha() method to check if the given string contains only alphabet characters.

# example 1
str = 'yusufshakeel'
print(str.isalpha())         # True

# example 2
str = '2018'
print(str.isalpha())         # False

# example 3
str = 'hello2018'
print(str.isalpha())         # False

# example 4
str = 'Yusuf Shakeel'
print(str.isalpha())         # False

# example 5
str = 'year-2018'
print(str.isalpha())         # False

Only example 1 is True and others are False because rest of them contains at least one non-alphabet character.

isdigit

This method will return True if all the characters in the given string is digit characters (0-9), False otherwise.

In the following example we are using isdigit() method to check if the given string contains only digit characters.

# example 1
str = 'yusufshakeel'
print(str.isdigit())         # False

# example 2
str = '2018'
print(str.isdigit())         # True

# example 3
str = 'hello2018'
print(str.isdigit())         # False

# example 4
str = 'Yusuf Shakeel'
print(str.isdigit())         # False

# example 5
str = 'year-2018'
print(str.isdigit())         # False

Only example 2 is True and others are False because rest of them contains at least one non digit characters.

isnumeric

This method will return True if all the characters in the given string is numeric characters (0-9), False otherwise.

Use only on unicode object. So, we will put u character before the strings like u"2018" or u"Yusuf Shakeel".

In the following example we are using isnumeric() method to check if the given string contains only numeric characters.

# example 1
str = u'yusufshakeel'
print(str.isdigit())         # False

# example 2
str = u'2018'
print(str.isdigit())         # True

# example 3
str = u'hello2018'
print(str.isdigit())         # False

# example 4
str = u'Yusuf Shakeel'
print(str.isdigit())         # False

# example 5
str = u'year-2018'
print(str.isdigit())         # False

Only example 2 is True and others are False because rest of them contains at least one non numeric characters.

islower

This method will return True if all the case based characters in the given string are lower case alphabet characters (a-z), False otherwise.

In the following example we are using islower() method to check if the given string contains alphabet characters and all of those alphabet characters are in lower case.

# example 1
str = 'yusufshakeel'
print(str.islower())         # True

# example 2
str = '2018'
print(str.islower())         # False

# example 3
str = 'hello2018'
print(str.islower())         # True

# example 4
str = 'Yusuf Shakeel'
print(str.islower())         # False

# example 5
str = 'year-2018'
print(str.islower())         # True

Example 1 is True as it contains alphabet characters and they are all in lower case.

Example 3 and 5 are True as they contains alphabet characters along with non alphabet characters. But all the alphabet characters are in lower case.

Example 2 is False as it contains only digits.

Example 5 is False as it contains alphabet and non alphabet characters but not all alphabet characters are in lower case.

isupper

This method will return True if all the case based characters in the given string are upper case alphabet characters (A-Z), False otherwise.

In the following example we are using isupper() method to check if the given string contains alphabet characters and all of those alphabet characters are in upper case.

# example 1
str = 'yusufshakeel'
print(str.isupper())         # False

# example 2
str = '2018'
print(str.isupper())         # False

# example 3
str = 'hello2018'
print(str.isupper())         # False

# example 4
str = 'Yusuf Shakeel'
print(str.isupper())         # False

# example 5
str = 'year-2018'
print(str.isupper())         # False

# example 6
str = 'HELLO'
print(str.isupper())         # True

Only example 6 is True as it contains alphabet characters and in upper case.

isspace

This method will return True if all the characters in the given string are whitespace characters, False otherwise.

In the following example we are using isspace() method to check if the given string contains only whitespace characters.

# example 1
str = '   '
print(str.isspace())         # True

# example 2
str = '	'
print(str.isspace())         # True

# example 3
str = 'hello2018'
print(str.isspace())         # False

# example 4
str = 'Yusuf Shakeel'
print(str.isspace())         # False

# example 5
str = 'year-2018'
print(str.isspace())         # False

Only example 1 and 2 contains whitespace characters other have a mix of characters.

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT