String Manipulation in Python29 Aug 2024 | 6 min read In this tutorial, we will learn some cool operations to manipulate the string. We will see how we can manipulate the string in a Pythonic way. Strings are fundamental and essential data structures that every Python programmer works with. In Python, a string is a sequence of characters enclosed within either single quotes ('...') or doubles quotes ("..."). It is an immutable built-in data structure, meaning once a string is created, it cannot be modified. However, we can create new strings by concatenating or slicing existing strings. Now let's understand the must-known Python string operation tricks. 1. String Padding: Add Extra Character ElegantlyString padding is a term to adding characters to the beginning or end of a string until it reaches a certain length. It can be useful in formatting text to align with other data or to make it easier to read. In Python, you can pad a string using the str.ljust(), str.rjust(), and str.center() methods. Here's an example of padding a string with spaces using the str.ljust() method: Example - Output: Python In the above example, the ljust() method adds spaces to the end of the string until it is ten characters long. We can also specify the padding character by passing it as an argument to the method: Output - Output: ----Python In this example, the rjust() method adds dashes to the beginning of the string until it is ten characters long. The str.center() method can be used to center the string within a certain width: Example - Output: **Python** 2. String SplittingString splitting refers to dividing a string into multiple substrings based on a specified delimiter or separator. In Python, you can split a string using the str.split() method. Here's an example of splitting a string based on whitespace characters. Example - Output: ['Hello', 'world,', 'how', 'are', 'you', 'today?'] In this example, the split() method returns a list of substrings, where each substring corresponds to a word in the original string. We can also specify a different separator to split the string: Example - Output: ['apple', 'banana', 'orange', 'grape'] In the above example, the split() method splits the string based on commas and returns a list of substrings, where each substring corresponds to a fruit in the original string. By default, the split() method splits the string based on whitespace characters. However, you can also specify a different separator using the sep argument. Example - In this example, the split() method splits the string based on dashes (-) and returns a list of substrings, where the first two substrings correspond to the first and second fruits, and the third substring corresponds to the remaining fruits. The maxsplit argument specifies the maximum number of splits to perform. 3. Use F-Strings for String FormattingThe f-strings are a feature in Python 3.6 and above that allow to embed expressions inside string literals. They are a convenient way to create strings containing dynamic values or format strings with variable values. Let's understand the following example. Example - Output: Hello, my name is Alice and I'm 30 years old. We can also format value in a specific way. Example - Output: The price is $12.35 4. Eliminating Unnecessary Character of a StringPython's strip() method is useful for data cleaning, especially when removing unnecessary characters from the beginning or end of strings. Data scientists often find data cleaning tedious, but Python's built-in string manipulation methods make it easier to remove unwanted characters from strings. The strip() method, in particular, can remove leading or trailing characters from a string. Example - Output: Hello, World Explanation - In the above code, the strip() method is used to remove the exclamation marks (!) from the beginning and end of the text string. The resulting string, clean_text, contains only the text content without any unnecessary characters. Note that the strip() method only removes characters from the beginning and end of a string. If you want to remove characters from within a string, you can use other string manipulation methods, such as replace() or regular expressions. 5. Concatenate StringsIn Python, we can concatenate strings using the + operator. Below is an example: Example - Output: Hello world In the above example, we first define two strings string1 and string2. We then concatenate them using the + operator, and add a space between them to create a new string called result. Finally, we print out the result string using the print() function. In another way, we can use the join() method to concatenate strings. Let's understand the following example. Example - Output: apple banana cherry In the above code, we first define a delimiter variable, which is set to a space character. We then define a list called my_list, which contains three strings. We use the join() method on the delimiter variable, passing in the my_list list as an argument. The join() method joins the strings in the my_list list together with the delimiter between them and returns a new string called result. Finally, we print out the result string using the print() function. 6. Search for Substring EffectiveFinding search string is a common requirement in daily programming. Python comes with the two methods. One is find() method - Example - Output: 17 35 The second method is index() - Example - Output: 17 35 # ValueError: substring not found As we can see that, Python's find() method returned -1 in case of string not found. However, index() method raised an error. 7. Leverage Regular Expression for Complex String HandlingRegular expressions (regex) are a powerful tool for handling complex string manipulation tasks in Python. They allow us to search for patterns within strings, extract information, and perform substitutions based on those patterns. To use regex in Python, we first need to import the re module. Here's a simple example of using regex to search for a pattern in a string: Let's understand the following example. Example - Output: Match Found Explanation - In the above code, we search for the pattern "fox" in the string "The quick brown fox jumps over the lazy dog." The re.search() function returns a match object if the pattern is found, and None otherwise. We use an if statement to check if a match was found, and print the appropriate message. Let's understand another example of using regex in Python - Example - Explanation - In the above example, we use regex to extract the name and age from a string that has a specific format. The pattern r"(\w+) (\w+) \((\d+) years old\)" matches a first name, last name, and age in parentheses. We use the match.group() method to extract the matched groups and print them. 8. Easy way to Remove StringGenerally, we use the loop to reverse the given string; it can be also reversed using the slicing. However, it is not a Pythonic way. Let's see the following example. Example - Output: reteP Next TopicAlexa Python Development |
As we all know that, Python is an object-oriented programming language. Therefore, Python follows all the concepts of OOPs, and one of such concepts is inheritance. While using the inheritance concept, we can refer to a parent class with the use of super() function inside the inherited...
4 min read
The logarithm function is the inverse of the exponential function. If we have an exponential equation, such as 2^3 = 8, we can rewrite it as a logarithmic equation: log2(8) = 3. Python's log base 2 functions can be accessed through the built-in math module. The...
2 min read
In this tutorial, we will learn how to build an easy notepad using Python by using Tkinter. The notepad GUI comprises different options like file and edit. All the functions, such as saving the file, opening the document, editing it, and copying and pasting, are possible. Python,...
4 min read
Introduction: In this tutorial, we learn about the strong password suggester Python Program. A strong password is needed to build strong security. It has become important to keep secure every device, social media account, bank account, ATM, important document, etc. We use a password to lock in...
7 min read
Introduction In Python, a private method is a method that is not intended to be used outside of the class in which it is defined. These methods are denoted by a double underscore prefix (__) before their name, and they can only be accessed within the class...
3 min read
In the following tutorial, we will learn how to build an age calculator with the help of the Tkinter library in the Python programming language. But before we get started, let us understand what Age Calculator is and how it works. What is an Age Calculator? An age calculator...
43 min read
Python provides a powerful module called collections that includes many useful data structures beyond the built-in types like lists and dictionaries. One particularly useful module in collections is collections.abc, which provides a set of abstract base classes for collections. In this article, we will explore the...
5 min read
The Knight's Tour problem is a classic problem in the field of computational mathematics and computer science. It is a puzzle where a chess knight is placed on an empty chess board and the goal is to move the knight to every square on the board...
7 min read
The Raspberry Pi is a low-cost, credit-card-sized computer developed in the UK by the Raspberry Pi foundation to support the teaching of fundamental computer science in educational institutions. Since then, it has gained popularity among makers, enthusiasts, and specialists for various projects. Python is a popular, high-level...
25 min read
Machine learning is utilized to tackle the regression question using two different algorithms to perform regression analysis: logistic regression and linear regression. These are the most widely used regression approaches. Regression analysis approaches in machine learning come in many algorithms, and their use depends on...
12 min read
We request you to subscribe our newsletter for upcoming updates.
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India