Is there a pythonic way to insert an element into every 2nd element in a string?
I have a string: 'aabbccdd' and I want the end result to be 'aa-bb-cc-dd'.
I am not sure how I would go about doing that.
To insert a character after every N characters, call the replace() method on the string, passing it the following regular expression - str. replace(/. {2}/g, '$&c') . The replace method will replace every 2 characters with the characters plus the provided replacement.
The + operator lets you combine two or more strings in Python. This operator is referred to as the Python string concatenation operator. The + operator should appear between the two strings you want to merge. This code concatenates, or merges, the Python strings “Hello ” and “World”.
Alexander Davison. You can "add" (concatenate) the period character to the end of the string. For example: "Harpreet is learning Python" + "!" # This code returns "Harpreet is learning Python!"
Method #2 : Using zip() + join() In this, zip function converts the characters to iterable tuples, split function is used to separate odd and even characters. Then list comprehension is responsible to convert the tuples to list of strings and at last result is joined using the join function.
>>> s = 'aabbccdd' >>> '-'.join(s[i:i+2] for i in range(0, len(s), 2)) 'aa-bb-cc-dd'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With