Table of Contents
< All Topics
Print

Easy Learning, Python Strings QAs for Beginner to Pro Part-3 (String Functions)

Python offers a variety of string functions that make text manipulation straightforward and efficient. String functions like capitalize() and upper() help in adjusting the case of strings, while count() and find() are useful for searching within strings. For formatting, format() and join() come in handy. The pre-requisite to understand the functionality and uses of these string functions is Easy Learning, Python Strings QAs for Beginner’s to Pro Part-2

Functions such as replace() and split() allow for modifying and breaking down strings, respectively.

Additionally, methods like isalnum(), isalpha(), and isdigit() help in validating string content. These functions collectively provide a robust toolkit for handling and processing strings in Python, making it a versatile language for text-based operations. For your better understanding here are some commonly used string functions in a form of general QnA.

Can You List Out Some Common Python String Functions

Yes, here are commonly used python string functions:

MethodDescription
capitalize()It capitalizes the first character of the String. This function is deprecated in python3
casefold()It returns a version of s suitable for case-less comparisons.
center(width, fillchar)It returns a space padded string with the original string centred with equal number of left and right spaces.
count(string, begin, end)It counts the number of occurrences of a substring in a String between begin and end index.
decode(encoding = ‘UTF8’, errors = ‘strict’)Decodes the string using codec registered for encoding.
encode()#capitalizefunctionEncode S using the codec registered for encoding. Default encoding is ‘utf-8’.
endswith(suffix ,begin=0, end=len(string))It returns a Boolean value if the string terminates with given suffix between begin and end.
expandtabs(tabsize = 8)It defines tabs in string to multiple spaces. The default space value is 8.
find(substring, beginIndex, endIndex)It returns the index value of the string where substring is found between begin index and end index.
format(value)It returns a formatted version of S, using the passed value.
index(subsring, beginIndex, endIndex)It throws an exception if string is not found. It works same as find() method.

capitalize()

The function capitalize() modifies the input by capitalizing the very first character of the string provided to it. This is one among the most commonly used string functions when data has to be used for some sort of data analysis job.

It is important to note that this particular function is now considered deprecated in Python version 3, meaning it is no longer recommended for use.

str1 = "ezylearning"  

str2 = str1.capitalize()  

print("Old value:", str1)  
print("New value:", str2) 
#Output:

Old value: ezylearning
New value: Ezylearning

casefold()

It provides a version of the string str that ignores differences in letter casing, allowing for a comparison that is not sensitive to whether the letters are in uppercase or lowercase.

str = "EZYlearning"  
 
str2 = str.casefold()  

print("Old value:", str)  
print("New value:", str2)  
#Output:

Old value: EZYlearning
New value: ezylearning

center(width ,fillchar)

It produces a string that has been padded with spaces, ensuring that the original string is positioned at the center. This formatting includes an equal number of spaces on both the left and right sides of the original content, creating a symmetrical appearance.


str = "Hello Dear Learner"  

str2 = str.center(60)  

print("Old value:", str)  
print("New value:", str2) 

str3 = str.center(60,'*')  
print("New filled value:", str3) 
#Output:

Old value: Hello Dear Learner
New value:                      Hello Dear Learner                     
New filled value: *********************Hello Dear Learner*********************

count(string,start,end)

This function counts the number of times a specific substring appears within a given string, but it only does so within the boundaries set by the specified start and end indices.

Syntax: count(sub[, start[, end]])

Parameters
  • sub (required): a substring which you want to be matched.
  • start (optional): a location from where the searching starts. Default value is starting index i.e. zero.
  • end (optional): If start is given then third argument will be treated as the end point to stop the search.
Return Type
  • It returns number of occurrences of substring in the range.
str = "Hello PSIT"  
str2 = str.count('l')  
# Displaying result  
print("occurrences:", str2)  
#OUTPUT:

occurrences: 2
str = "ab bc ca de ed ad da  ab bc ca"  
ct = str.count('a')  
# Displaying result  
print("occurrences:", ct)  
#OUTPUT:

occurrences: 6
str = "ab bc ca de ed ad da ab c ca"  
ct = str.count('a')  
print("occurrences:", ct)  

ct = str.count('a', 3) # 3-> from where to start 
print("occurrences:", ct) 

ct = str.count('a', 3, 8)  # 3--> start  8--> end
print("occurrences:", ct)  
#OUTPUT:

occurrences: 6
occurrences: 5
occurrences: 1

Decode()

  • Decodes the string using codec registered for encoding.
# Define a bytes object
str1='Hello, Python!'
print(str1)

bytes_data = b'Hello, Python!'
print(bytes_data)

# Decode bytes object to string using UTF-8 encoding
text = bytes_data.decode('utf-8')

print(text)  # Output: Hello, Python!
#OUTPUT:

Hello, Python!
b'Hello, Python!'
Hello, Python!

encode() function

  • Python encode() method encodes the string according to the provided encoding standard.
  • By default Python strings are in unicode form but can be encoded to other standards also.
  • Encoding is a process of converting text from one standard code to another.

Syntax

encode(encoding=”utf-8″, errors=”strict”)

Parameters
  • encoding : encoding standard, default is UTF-8
  • errors : errors mode to ignore or replace the error messages.
  • Both are optional. Default encoding is UTF-8.

Error parameter has a default value strict and allows other possible values ‘ignore’, ‘replace’, ‘xmlcharrefreplace’, ‘backslashreplace’ etc too.

Return Type
  • It returns an encoded string.
# Example-2

# Latin caharacter Ë into default encoding.  
# Variable declaration  

str = "HËLLO"  
ecd = str.encode()  
 
print("Old value", str)  
print("Encoded value", ecd) 
#OUTPUT:

Old value HËLLO
Encoded value b'H\xc3\x8bLLO'
# Example 3
#We are encoding latin character into ascii, it throws an error. See the example below

str = "HËLLO"  
ecd = str.encode("ascii") 

# Displaying result  
print("Old value", str)  
#print("Encoded value", ecd)  
#Output:

---------------------------------------------------------------------------
UnicodeEncodeError                        Traceback (most recent call last)
Cell In[91], line 5
      1 # Example 3
      2 #We are encoding latin character into ascii, it throws an error. See the example below
      4 str = "HËLLO"  
----> 5 ecd = str.encode("ascii") 
      7 # Displaying result  
      8 print("Old value", str)

UnicodeEncodeError: 'ascii' codec can't encode character '\xcb' in position 1: ordinal not in range(128)
# Example 4
# If we want to ignore errors, pass ignore as the second parameter.
 
str = "HËLLO"  
ecd = str.encode("ascii","ignore")  
 
print("Old value", str)  
print("Encoded value", ecd)  
#Output:

Old value HËLLO
Encoded value b'HLLO'
# Example 5
#It ignores error and replace character with ? mark.

str = "HËLLO"  
ecd = str.encode("ascii","replace")  
 
print("Old value", str)  
print("Encoded value", ecd) 
#Output:

Old value HËLLO
Encoded value b'H?LLO'

endswith() Method

  • It returns true of the string ends with the specified substring, otherwise returns false.

Syntax:

endswith(suffix[, start[, end]])

Parameters
  • suffix : a substring
  • start : start index of a range (Optional)
  • end : last index of the range(Optional)
  • Start and end both parameters are optional.
Return Type
  • It returns a Boolean value either True or False.
#Example 1
#A simple example which returns true because it ends with dot (.).

str = "Hello this is MyLearning@EzyLearning."  
isends = str.endswith("EzyLearning.")  
 
print(isends)  
#Output:

True
# Example 2
# It returns false because string does not end with is.
str = "Hello this is EzyLearning@PSIT."  
isends = str.endswith("is")  

print(isends)
#Output:

False
# Example 3
#Here, we are providing start index of the range from where method starts searching.

str = "Hello this is EzyLearning@PSIT."
isends = str.endswith("is",10)  # 10--> start index
  
print(isends)  
#Output:

False
# Example 4
# It returns true because third parameter stopped 
# the method at index 13.

 
str = "Hello this is Kanpur."  
isends = str.endswith("is",0,13)  

print(isends) 
#Output:

True

expandtabs() Method

The expandstabs() method in Python is designed to replace all tab characters within a string with a specified number of spaces. By default, each tab character is expanded to eight spaces, but this behavior can be modified or overridden based on specific requirements or preferences of the programmer. This flexibility allows for more control over the formatting of output, ensuring that the spacing between elements can be adjusted to meet various coding standards or personal styles.

We can pass 1, 2, 4 and more to the method which will replace tab by these number of space characters.

Syntax

expandtabs(tabsize=8)

Parameters

tabsize : It is optional, and default value is 8.

Return Type

It returns a modified string.

# Example


str = "Welcome \t to \t the \t My website EzyLearn.in."  
 
str2 = str.expandtabs(10)  
  
print(str2)   
#Output:

Welcome    to        the       My website EzyLearn.in.

find() Method

  • One of the most powerful tools among the string functions in Python.
  • This find () method finds a substring in the whole String and returns the index of the first match.
  • It returns -1 if the substring does not match.

Syntax:

string.find(substring [, start[, end]])

Parameters:
  • Stringis the String in which you want to search for the substring
  • Substringis the String you want to search for
  • Startis the index from which the search should begin (optional, defaults is 0)
  • Endis the index at which the search should end (optional, defaults to the end of the String)
# Example-1
string = "Hello, world!"  
substring = "world"  
index = string.find(substring)  
print(index) 

index = "Hello, world!".find("world" )  
print(index) 
#Output:

7
7
# Example-2

string = "Hello, world!"  
substring = "l"  
start = 3  
end = 8  
index = string.find(substring, start,end)  
print(index) 
#Output:

3
# Example-3

string = "Hello, world!"  
substring = "python"  
index = string.find(substring)  
print(index)  
#Output:

-1

Write a program to Find a substring in a string with multiple occurrences.


# Finding a substring in a string with multiple occurrences:

string = "Hello, world!"
substring = "l"
index = string.find(substring)
while index != -1:
print(index)
index = string.find(substring, index + 1)
#Output:

2
3
10

Leave a comment