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.
Yes, here are commonly used python string functions:
Method | Description |
---|---|
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()#capitalizefunction | Encode 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. |
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
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
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*********************
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.
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
# 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!
Error parameter has a default value strict and allows other possible values ‘ignore’, ‘replace’, ‘xmlcharrefreplace’, ‘backslashreplace’ etc too.
# 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'
#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
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.
tabsize : It is optional, and default value is 8.
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.
# 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
# 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
All about java servlets Part-2 What is a website? Website is a collection of related…
Let's train the machine. Machine learning is a growing technology which enables computers to learn…
“Unless you try to do something beyond what you have already mastered, you will never…
Whenever you decide to start coding and you want to become budding coder or programmer…
C components are essential elements of a C program, including comments, preprocessor directives, functions, statements,…
All about java servlets Part-2 What is a website? Website is a collection of related…