Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Python String Methods | Functions with Example

A String in Python is an object with lots of methods and functions in it. In Python, a function defined with respect to a particular object is called method.

A string method does not modify the original string. It always creates (or returns) a new string.

Some of the string methods takes a number of arguments and some are associated with only string objects. The general syntax of string methods is as follows:

Syntax:
1. string_obj.method()
2. string_obj.method(arguments)

For example:

str = "python"
print(str.capitalize()) # calling a method with no argument.

str = "Python programming language"
print(str.find("programming")) # calling a method with one argument. 

Note that in string functions, we use a dot (.) operator along with string to access string functions except len() function.

Python String Methods


There are several built-in methods associated with string data type to support various operations in Python. Built-in methods are those that are defined by Python programming language and are always available for us to use.

Let’s understand some of the most common string methods with the help of examples.

(1) len():

The len() function is used to find the length of a string. It returns the total number of characters in a string is holding. The general syntax to call len() function is:

len(str)

Example:

str = "Hello World!"
print(f"Length of string '{str}' is",len(str))
Output:
      Length of string 'Hello World!' is 12

(2) count():

The count() function counts the number of same characters that are present within a string.

Example:

str = "Python is an object oriented programming language."
substr = "object"
print(str.count(substr))
substr = "a"
print(str.count(substr))
Output:
      1
      4


(3) capitalize():

The capitalize() function returns a copy of string with first letter capitalized.

Example:

str = "language"
print(str.capitalize())
Output:
      Language

In the above code, the first character is capitalized as ‘L’ instead of ‘l’.

(4) lower():

The lower() function converts all the characters of the string into lower case string.

Example:

str = "SCIENTECH EASY"
print(str.lower())
Output:
      scientech easy

(5) islower():

This function checks whether all the characters of a string are in lowercase or not. It returns true if all characters in a string are lowercase. Otherwise, it returns false.

Example:

str1 = "Technology"
print(str1.islower())

str2 = "technology"
print(str2.islower())
Output:
      False
      True

(6) upper():

This function converts all characters of a string into uppercase string. If a string is already in uppercase, it will remain in that form. But, if it is in lowercase, the upper() method will convert into uppercase string.

Example:

str = "Technology"
print(str.upper())
Output:
      TECHNOLOGY

(7) isupper():

This method checks whether all characters of a string are in uppercase or not. If all the characters in the string are uppercase, it returns true. Otherwise, it returns false.

Example:

str = "Technology"
print(str.isupper())

str2 = "TECHNOLOGY"
print(str2.isupper())
Output:
      False
      True

(8) find():

This method returns the index position of first occurrence of substring in a specified string. It returns -1 if substring is not found in the specified string.

Example:

str = "I love Python coding."
print(str.find("love"))
print(str.find("Python"))
Output:
      2
      7

(9) isalnum():

The isalnum() method checks whether a string contains alphanumeric characters (no space, and special characters) or not. It returns true if all characters in the string are alphanumeric. Otherwise, it returns false.

Example:

str = "CBSEExam2023" # alphanumeric characters.
print(str.isalnum())

str2 = "CBSEExam-2024" # mix characters.
print(str2.isalnum())
Output:
      True
      False

(10) isalpha():

The isalpha() method checks whether or not the string contains alphabetic characters only. It returns true if all characters in the string are alphabetic (no space, special characters, and digits). Otherwise, it returns false.

Example:

str = "CBSEExam" # only alphabetic characters.
print(str.isalpha())

str2 = "CBSE Exam2024" # space and number characters.
print(str2.isalpha())
Output:
      True
      False

(11) isdigit():

The isdigit() method checks whether the string contains digits only or not. This method returns true if all characters in the string are digits. Otherwise, it returns false.

Example:

str = "2024" # only digits.
print(str.isdigit())

str2 = "2024-2025" # mix characters.
print(str2.isdigit())
Output:
      True
      False

(12) isnumeric():

The isnumeric() method checks whether or not the string contains only numeric characters. It returns true if all characters in the string are numeric, otherwise it returns false value.

Example:

str = "2024" # only numeric characters.
print(str.isnumeric())

str2 = "2024 2025" # space.
print(str2.isnumeric())
Output:
      True
      False

(13) index():

The index() function basically returns the index of a substring inside the specified string.

Example:

str = "I is a vowel"
substr = "a"
print(str.index(substr))
Output:
      5

(14) startswith():

The startswith() method returns true value if the string begins with the specified substring. Otherwise, it returns false value.

Example:

str = "I is a vowel"
substr = "I"
print(str.startswith(substr))
print(str.startswith("is"))
Output:
      True
      False

(15) endswith():

The endswith() method returns true value if a string ends with the specified substring otherwise, it returns false value.

Example:

str = "Python is object oriented programming language"
strends = "language"
print(str.endswith(strends))
print(str.endswith("programming"))
Output:
      True
      False

(16) max() and min():

The max() and min() methods return the highest and lowest alphabetical character based on ASCII value from the string.

Example:

str = "ABCDEFG"
print(max(str))
print(min(str))
Output:
      G
      A

In this example, the lowest character printed is A because of its ASCII value is 65. Whereas, the highest character printed is G because of its ASCII value is 71.

(17) swapcase():

This method converts all uppercase letters to lowercase and all lowercase letters to uppercase letters of the specified string and returns it.

Example:

str = "ScienTech EASY"
print(str.swapcase())
Output:
      sCIENtECH easy

(18) isupper():

This method checks whether all characters in the string are in the uppercase or not. It returns true value if all characters in the string are uppercase otherwise, returns false.

Example:

str1 = "SCIENTECH EASY"
str2 = "scientech easy"
print(str1.isupper())
print(str2.isupper())
Output:
      True
      False

(19) split():

This method splits the string into a comma separated list based on the specified separator delimiter and returns it.

Example:

str = "I#love#coding#in#Python"
print(str.split("#"))
Output:
      ['I', 'love', 'coding', 'in', 'Python']

(20) join():

This method joins the string in the sequence. It inserts a string between each character of the string sequence and returns the concatenated string.

Example:

seq = ("Every", "people", "love", "his", "country", "in", "the", "world.")
str = "-"
print(str.join(seq))
Output:
      Every-people-love-his-country-in-the-world.

(21) replace():

This method replaces one specific word by some another specified word.

Example:

str = "I love my country."
print(str.replace("country","India"))
Output:
      I love my India.

(22) title():

This method converts the first character of the string into uppercase and returns it.

Example:

str = "python is easy to learn"
print(str.title())
Output:
      Python Is Easy To Learn

(23) istitle():

This function checks whether each character in a string begins with an uppercase letter or not. It returns true if the string is title cases string and there is at least one character, otherwise, returns false.

Example:

str1 = "Python Language"
print(str1.istitle())

str2 = "Python language"
print(str2.istitle())
Output:
      True
      False

(24) isspace():

This function checks whether the string contains a white space character or not. If the string contains only whitespace character, it returns true otherwise, returns false.

Example:

str1 = "  "
print(str1.isspace())

str2 = "Python language"
print(str2.isspace())
Output:
      True
      False

(25) strip():

This method removes all leading and trailing whitespace character from a string.

Example:

str = " Python "
print(str.strip(),"is a powerful programming language.")
Output:
      Python is a powerful programming language.

(26) lstrip():

This method removes all leading whitespaces of a string.

Example:

str = "   Scientech   "
print(str.lstrip(),"is the best institute to learn technologies in Dhanbad.")
Output:
      Scientech    is the best institute to learn technologies in Dhanbad.

(27) rstrip:

This method removes all trailing white space character of a string.

Example:

str = "   Scientech   "
print(str.rstrip(),"is the best institute to learn technologies in Dhanbad.")
Output:
          Scientech is the best institute to learn technologies in Dhanbad.

(28) zfill():

The zfill() method adds zeros at the beginning of the string until it reaches the specified length.

Example:

str = "Language"
print(str.zfill(12))
Output:
       0000Language

In this tutorial, you have learned about various built-in Python string methods and functions with lots of examples. Hope that you will have understood the basic points of all Python functions and practiced all example programs.
Thanks for reading!!!

The post Python String Methods | Functions with Example appeared first on Scientech Easy.



This post first appeared on Scientech Easy, please read the originial post: here

Share the post

Python String Methods | Functions with Example

×

Subscribe to Scientech Easy

Get updates delivered right to your inbox!

Thank you for your subscription

×