Python | Insert character after every character pair

Python | Insert character after every character pair

To insert a character after every character pair in a string, you can use string slicing, string concatenation, or regular expressions. In this tutorial, we'll cover these methods.

Suppose you have the following string:

s = "abcdef" 

And you want to insert the character X after every pair of characters.

1. Using String Slicing:

You can slice every 2 characters from the string and join them with your desired character:

char_to_insert = "X" result = char_to_insert.join([s[i:i+2] for i in range(0, len(s), 2)]) print(result) # Outputs: "abXcdXef" 

2. Using a Loop:

You can loop through the string and use string concatenation:

char_to_insert = "X" result = "" for i in range(0, len(s), 2): result += s[i:i+2] + char_to_insert result = result.rstrip(char_to_insert) # Remove the extra inserted character at the end if it exists print(result) # Outputs: "abXcdXef" 

3. Using Regular Expressions:

Using the re module, you can match every pair of characters and substitute them:

import re char_to_insert = "X" result = re.sub(r'..', r'\0' + char_to_insert, s) print(result) # Outputs: "abXcdXef" 

Key Takeaways:

  • Using string slicing is a Pythonic and concise way to achieve the goal for short strings.

  • For very large strings, using a loop with string concatenation may be less memory-efficient due to the creation of many intermediate strings. In such cases, using a list to collect the parts and then joining them at the end would be more efficient.

  • Regular expressions provide a powerful method for string manipulations, and while it may be a bit overkill for this specific task, it's good to know how it can be done using re.


More Tags

masstransit mongodb-update logout show-hide entity-framework-4.1 polling azure-virtual-machine sql-drop windows-vista ssid

More Programming Guides

Other Guides

More Programming Examples