×

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

Best resources to learn Numpy and Pandas in python

In this tutorial, we will discuss the different resources where we can learn about NumPy and Pandas libraries of Python in a more efficient way. NumPy NumPy, a Python library used for...

4 minutes read.

Python map() function

Python map() function The map() function in Python returns an iterator that applies a function to every item of iterable, yielding the results. Syntax map(function, iterable, ...) Parameter function: It is a required parameter that represents the function to...

1 minute 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.

Best app for python

What is python? Python is a prevalent, general-purpose, and high-level programming language. Python Programming Language is appropriate for experienced programmers and also for beginners. Python programming language is being utilized by...

19 minutes read.

Python Scikit-image | Image Processing Using Scikit-Image

What is Image Processing? The world is defined with images and, every image has its different specialties. An image can contain much-needed information that can be helpful in various ways. The process...

4 minutes read.

Python filter() function

Python filter() function The filter() function constructs an iterator from those elements of iterable for which the parameter ‘function’ returns a Boolean value true. Syntax filter(function, iterable) Parameter function: This parameter represents a function to be run for each item in the...

1 minute read.

How to find square root in python

How to find Square Root of a number In Python Python makes a lot of tasks easier by using different functions, modules, and libraires. There is an inbuilt function in Python...

6 minutes read.

Accuracy_score Function in Sklearn

A crucial stage in data science is measuring our model's performance using the appropriate metric. In this article, we will examine two methods for calculating the accuracy of your predictions:...

13 minutes read.

Python Logging Maxbytes

Python: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

6 minutes read.

Paramiko Python Example

Python Programming Language Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It...

6 minutes read.

Python Operator Precedence

Before knowing about the operator precedence in Python, we have to know about the operators in Python. So let's have a look at it. According to one definition, the operator is...

3 minutes read.

Sentence to python vector

Conversion of a Sentence to Vector in Python Before starting the tutorial, let’s just recap about the vector and the respective package that has to be imported in Python. Python Vector: Putting simply,...

3 minutes read.

Cross Entropy in Python

Introduction Cross-entropy loss is frequently combined with the softmax function. Determine the total entropy among the distributions or the cross-entropy, which is the difference between two probability distributions. For the purpose...

5 minutes read.

Assertion Errors and Attribute Errors in Python

Assertion Error in Python In Python, the assert condition is used to continue the execution if the given statement displays true. If the assert statement displays false, it raises Assertion Error...

3 minutes read.

How to Import Files in Python

Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

3 minutes read.

Programs for Printing Pyramid Patterns in Python

<!-- wp:paragraph --><p>Python supports printing patterns using basic for loops. The number of rows is handled by the first outer loop, while the number of columns is handled by the...

9 minutes read.

To Do GUI Application using Tkinter in Python

GUI: One of the most significant factors that increased the usability of computer and digital technologies for common, less tech-savvy users is likely the development and widespread adoption of GUIs. GUIs...

3 minutes read.

Python 2.7 data structures

The rundown information type has a few additional techniques. Here is every one of the strategies for listing objects: list.append(x): Add a thing to the furthest limit of the rundown; comparable...

9 minutes read.

Io stringio Python

Python programming language: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a...

7 minutes read.

Python vars() Function

Python vars() Function The vars() function in Python returns the __dict__ attribute for a module, class, instance, or any other object with a __dict__ attribute. Syntax vars([object]) Parameter object: This parameter represents any object with a __dict__attribute Return This function returns...

1 minute read.