How to swap two characters in a string in python?29 Aug 2024 | 3 min read In this article, we will discuss how to swap two characters in a string. There are various approaches that will help to understand how we can swap two characters in a string. Approach 1: Using list() and join() MethodIf we want to swap two characters in a string, we can use the list() and join() method. Example: Output: hewlo lorld Explanation: In the code above, we first define the input string as "hello world". After that, we convert the string to a list of characters using the list() method. Next, we use tuple unpacking to swap the characters at index 2 and index 6 in the list. Finally, we convert the list back to a string using the join() method and output the new string Approach 2: Using slicing and concatenationIf we want to swap two characters in a string, we can use the slicing and concatenation method. Example: Output: hewlo lorld Explanaton: In this approach, we use string slicing and concatenation to swap the characters. We slice the string into four parts: the substring before the first character to be swapped (string[:2]), the first swapped character (string[6]), the substring between the swapped characters (string[3:6]), the second swapped character (string[2]), and the substring after the second swapped character (string[7:]). After that, we concatenate these substrings in the desired order to create the new string. Approach 3: Using a list comprehensionIf we want to swap two characters in a string, we can use the list comprehension method. Example: Output: hewlo lorld Explanation: In this approach, we create a list of characters using a list comprehension that iterates over the indices of the input string. We use a conditional expression within the list comprehension to swap the characters at index 2 and index 6. The expression string[6 if i == 2 else 2] returns the character at index 6 if the current index is 2, and returns the character at index 2 if the current index is 6. Otherwise, it returns the original character at the current index. After that, we convert the list of characters back to a string using the join() method and output the new string. This approach may be less efficient than the previous approaches because it creates a new list of characters, but it may be useful in situations where a list comprehension is more convenient or intuitive to use. Approach 4: Using 'bytearray' built-in typeIf we want to swap two characters in a string, we can use the bytearray method. Example: Output: hewlo lorld Explanation: In this approach, we first convert the input string to a bytearray using the bytearray() built-in function. After that, we specify the 'utf-8' encoding to convert the string to byte, and then we swap the two characters at index 2 and index 6 by directly accessing the corresponding elements in the bytearray. Finally, we convert the bytearray back to a string using the decode() method and output the new string. This approach is efficient because it uses a mutable bytearray instead of creating a new string or list. Next TopicHow to Use the Rich Library with Python |
In this tutorial, we will learn how to use the AST to understand the code. What is AST Module? The AST (Abstract Syntax Tree) module in Python provides tools for interacting with Python code on a structural level. An Abstract Syntax Tree is a tree representation of...
6 min read
Python is one of the computer languages that has advanced technology to a completely new level. The general-purpose programming language have found use in a wide range of industries, including software engineering, data science, natural language processing, and artificial intelligence. Python 2 and Python 3 were the...
3 min read
Playing with numbers is something that we are doing since our childhood. The basic arithmetic operations performed on numbers generate valuable results. In the voyage of learning, we must give more emphasis to the logic develop in mathematics as they become the foundation of programming. In this...
3 min read
In this tutorial, we will learn about one of the important applications of Depth-first Search. We will understand the concept of topology sorting, how it works and implements it using the Python programming language. Lastly, we will learn the time complexity of the algorithm and the...
3 min read
An Introduction to Faker Python provides an open-source library, also known as Faker that helps the user build their Dataset. We can generate random data using random attributes such as Name, Age, Location, and many more. The Faker library supports all central locations and languages beneficial to...
9 min read
The purpose of this post is to give readers a straightforward GUI application that allows them to view the current temperature in any city they choose. The technology also offers a straightforward user interface to make application simpler. It also offers its users a fantastic UX....
3 min read
In statistics, where data can assume many shapes and behaviors, distributions are crucial for understanding and modeling real-world phenomena. Among these, the Log-Laplace distribution is a versatile option for capturing heavy-tailed data patterns with a distinct logarithmic shape. With applications from financial modeling to anomaly detection,...
9 min read
A string is a succession of characters. A person is just an image. For instance, the English language has 26 characters. PCs don't manage characters; they manage numbers (twofold). Despite the fact that you might see characters on your screen, inside, it is put away and...
4 min read
We have worked with different kind of numbers in Python and modified their type as per our need. In this tutorial, we will discuss how we can remove decimal in Python. Let's start with a simple program, a = 24 print(type(a)) b = 19.4 print(type(b)) c = 3+4j print(type(c)) Output: <class 'int'> <class 'float'> <class 'complex'> Explanation: In the above...
2 min read
You can reverse the truth value of any Boolean expression or object with Python's not operator. This Python operator can be applied in boolean conditions like if-elif statements and for or while loops. It also functions in non-Boolean settings, enabling you to reverse the variables' truth...
8 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