×

Python String Methods

Python String Methods

Python has a set of built-in string methods. The Python string methods are as follows:

capitalize() The string.capitalize() method returns a copy of the string by converting the first character to upper case. 
center() The string.center() method returns a centered in a string of length width.
count() This method returns the number of times a specified value occurs in a string.
decode() The string.decode() method decodes the string using the codec registered for encoding.
encode() The string.encode() method returns an encoded version of the string
endswith() The string.endswith() method returns a boolean value true if the specified string ends with the given value.
expandtabs() This method returns a copy of the string where all tab characters are expanded using spaces.
find() The string.find () method returns the lowest index in the string where the substring is found else it returns -1.
index() The string.index() method returns the lowest index in the string where the substring is found else it raises a ValueError.
isalnum() This method returns a Boolean value True if all characters in the string are alphanumeric
isalpha() The string.isalpha() method returns True if all characters in thespecified  string are in the alphabet.
isdigit() The string.isdigit() method returns True if all characters in the string are in digits.
islower() The string.islower() method returns a Boolean value True if all characters in the specified string are in lower case.
isspace() The string.isspace() method returns true if there are only whitespace characters in the string else it returns false.
istitle() The string.istitle() method returns true if the string is a titlecased string and follows the rules of a tittle.
isupper() The string.isupper() method returns true if all cased characters in the string are uppercase else it returns false.
join() This method joins the elements of an iterable to the end of the string
ljust() The string.ljust() method returns a left justified version of the string.
lower() The string.lower() method returns a copy of the string converted to lowercase.
lstrip() This method returns a copy of the string with leading characters removed.
replace() The string.replace() method returns a string where a specified value is replaced with the old value.
rfind() The string.rfind() method returns the highest index in the string if the substring sub is found else it raises a ValueError.
rindex() This method return the highest index in the string if the substring is found else it returns -1.
rjust() The string.rjust() method returns a right justified version of the specified string of length width.
rsplit() This method returns a list of words in the string by splitting the string at the specified separator.
rstrip() The string.rstrip() method returns a right trim version of the string
split() The string.split() method splits the specified string at separators, and returns the list.
splitlines() This method splits the given string at line breaks and returns the list.
startswith() The string.startswith() returns a Boolean value true if the specified string starts with the given prefix, else it returns False.
strip() The string.strip() method returns a copy of the string by removing the  leading and trailing characters. 
swapcase() This method returns a copy of the string with uppercase characters converted to lowercase and vice versa.
title() The string.title() method returns the titles cased string by converting the first character of each word to upper case.
translate() The string.translate() method returns a copy of the translated string.
upper() The string.upper() method returns a copy of the string converted to uppercase.
zfill() The string.zfill() method returns the numeric string left filled with a specified number of 0 values at the beginning.

Example 1

 # Python program explaining
 # the string methods
 # passing the string value
 strVal = "hello world"; 
 print("String value:",strVal)
 # the capitalize() method
 # capitalizing the first character of the String
 print ("After capitalizing the string:", strVal.capitalize())
 # the center() method
 # centering the string with length 40 and fillchar '!'.
 print("After the center() method:")
 print ( strVal.center(40, '!'))
 # the count() method
 # returning the count of alphabet 'e'
 print ("\nThe count of 'e' in the string is", strVal.count('e'))
 # the isalnum() method
 # validating if and else condition
 if strVal.isalnum() == True:
    print("\nAll characters of specified string are alphanumeric.")
 else:
     print("\nAll the characters are not alphanumeric.") 

Output

 String value: hello world
 After capitalizing the string: Hello world
 After the center() method:
 !!!!!!!!!!!!!!hello world!!!!!!!!!!!!!!!
 The count of 'e' in the string is 1
 All the characters are not alphanumeric. 

Example 2

 # Python program explaining
 # the string methods
 # initializing the string 
 strVal = "Hello everyone, welcome to my world."
 print("The string:",strVal)
 # passing the substring
 substring="welcome"
 # the index() method
 # returning the lowest index in the string if the substring
 index = strVal.index(substring)
 # prinitng the index of the specified substring
 print("The index of '",substring,"' is",index)
 # the find() method
 find= strVal.find('to')
 # prinitng the index of the specified substring
 print("The index of '",substring,"' is",find)
 # the isdigit() method
 result = strVal.isdigit()
 # printing the isdigit() result
 print("The isdigit() method returns: ",result)
 # the islower() method
 # checking whether the passed string is in a lower case or not
 result = strVal.islower()
 # printing the islower() result
 print("The islower() method returns: ",result) 

Output

 The string: Hello everyone, welcome to my world.
 The index of ' welcome ' is 15
 The index of ' welcome ' is 23
 The isdigit() method returns:  False
 The islower() method returns:  False 

Example 3

 # Python program explaining
 # the string methods
 # the isspace() method
 strVal = "   \t"
 print("String 1=",strVal)
 print("The isspace() method returns: ",strVal.isspace())
 # the isupper() method
 string = 'TUTORIALSANDEXAMPLES'
 print("\nString 2:",string)
 print("The above string is upper cased:",string.isupper())
 # the join() method
 string3 = 'Hello'
 string4 = '!!!'
 # concatenating each character of string2 to the front of string1
 print('\nstring3.join(string4):', string3.join(string4))
 # concaneting each character of string1 to the front of string1
 print('string4.join(string3):', string4.join(string3))
 # the lower() method
 # initializing the string
 string5 = "HELLO WORLD"
 print("\nString5:",string5)
 # converting the string to lower case
 lowStr = string5.lower()
 print("After converting it in lower case:",lowStr)
 # the title() method
 string6 = "My Favourite Teacher"
 print("\nString 6:",string6)
 # will return true
 print("The above string is Titlecased:",string6.istitle())  

Output

 String 1=     
 The isspace() method returns:  True
 String 2: TUTORIALSANDEXAMPLES
 The above string is upper cased: True
 string3.join(string4): !Hello!Hello!
 string4.join(string3): H!!!e!!!l!!!l!!!o
 String5: HELLO WORLD
 After converting it in lower case: hello world
 String 6: My Favourite Teacher
 The above string is Titlecased: True 

Related Topics

Class and Static Methods in Python

The method is an important concept to learn for every programmer or data analyst. We know that in OOP's concept, each object has its attributes and behaviors defined through methods....

3 minutes read.

Python Permutations and Combinations

In mathematics, we all studied what is meant by permutations and combinations. “Permutations” define the way of arranging the elements in sequential order. “Combinations” mean the way of selecting the...

7 minutes read.

Multiprocessing in python

The word multiprocessing is used to compute the operation in which more than two processors run simultaneously with more than one central processor. The computer's performance increases gradually. Multiprocessing is...

6 minutes read.

List Comprehension in Python

Sometimes we need new lists that are completely based on previously existing lists, so to perform this operation successfully, some of the programming languages come with a syntactic construct known...

5 minutes read.

Convert uppercase to lowercase in Python

Python String lower() By using the built-in string lower() method, all the uppercase characters can be converted into lowercase characters in a string, The lowercased string from the given string is returned...

1 minute read.

Add in Dictionary Python

Dictionary in python: Dictionaries are a useful data configuration for storing information in Python because they can mimic real-world data arrangements where a particular value exists for a particular key. The...

4 minutes read.

Python hex() function

Python hex() function The hex() function in Python  converts the specified number into a hexadecimal value. Syntax hex(x) Parameter x: The parameter represents an Integer value. Return This function Returns hexadecimal string. Example 1 # Python Program explaining # the hex() function print("The...

1 minute read.

Python Program to Print all the Prime Number in an Interval

Python Program to Print all the Prime Number in an Interval What is Prime numbers? A prime number is referred to those numbers that can be divisible by them only. In simple words,...

4 minutes read.

Inheritance in Python

Inheritance in Python Object-Oriented Programming provides reusable patterns to the code for restricting the redundancy in development projects. One of the basic principles of Object-Oriented Programming that helps achieve recyclable code...

8 minutes read.

Python complex() class

Python complex() class The complex() class in Python returns a complex number or converts a string or number to a complex number. Syntax class complex([real[, imag]]) Parameter Real: This parameter consists of a number representing the real...

1 minute read.

iobase Python

All I/O flow classes derive from this conceptual base class. Derived classes will have to execute several of the class's abstract data types. The loop method is supported by all members of...

4 minutes read.

What is Python compiler GDB?

The source code of one programming language is converted into machine code, bytecode, or another programming language by a compiler, a specialised software. A compiler is a tool that converts high-level...

3 minutes read.

Python md5_file() function

Python md5_file() function The md5_file() function in PHP calculates the md5 hash of a given file. Syntax md5_file ( string $filename [, bool $raw_output ] )  Parameter filename(required)- This parameter signifies the file to be calculated. raw_output(optional)- It takes a boolean value that specifies hex or binary...

1 minute read.

Matrix List Comprehension in Python

Introduction One of Python's most beautiful features is list comprehension. Iterating over an iterable object to create lists is a clever and succinct method. Nested List or matrix list Comprehensions, which...

6 minutes read.

Python Strong Number

Strong Number- Logic Divide each of the number's digits into separate units to determine if it is a strong number or not.The factorial of each digit must then be determined. The...

5 minutes read.

Python Program to Find the gcd of Two Numbers

Introduction Greatest Common Divisor is the full form of gcd. The greatest common divisor, or GCD, of two numbers, is a value that can exactly divide the two digits and is...

5 minutes read.

Python program to find the area of the triangle

Python program to find the area of the triangle This article will discuss how to find the area of a triangle in Python with all three given sides. The area of...

2 minutes read.

How to Take Input in Python

How To Take Input In Python Python has various in-built functions that help in code redundancy. Let's discuss the usage of some functions- ascii() – it returns a readable representation of objects.format()...

4 minutes read.

Difference between Input() and raw_input() functions in Python

There are two input functions in Python that are used for taking input are given below: raw_input()input() What is raw_input() Function? raw_input() function is a built-in function in Python. It is used to...

6 minutes read.

Python Tutorial

Python tutorial is a widely used programming language which helps beginners and professionals to understand the basics of Python programming easily. Python is a high-level, easy, interpreted, general-purpose, and dynamic programming...

19 minutes read.