I want to insert some text before a substring in a string.
For example:
str = "thisissometextthatiwrote"
substr = "text"
inserttxt = "XX"
I want:
str = "thisissomeXXtextthatiwrote"
Assuming substr can only appear once in str, how can I achieve this result? Is there some simple way to do this?
Using a character array Get the both strings, suppose we have a string str1 and the string to be added at begin of str1 is str2. Create a character array with the sum of lengths of the two Strings as its length. Starting from 0th position fill each element in the array with the characters of str2.
Python add strings with + operator The easiest way of concatenating strings is to use the + or the += operator. The + operator is used both for adding numbers and strings; in programming we say that the operator is overloaded. Two strings are added using the + operator.
If you need to insert a given char at multiple locations, always consider creating a list of substrings and then use . join() instead of + for string concatenation. This is because, since Python str are mutable, + string concatenation always adds an aditional overhead.
Why not use replace
?
my_str = "thisissometextthatiwrote"
substr = "text"
inserttxt = "XX"
my_str.replace(substr, substr + inserttxt)
# 'thisissometextXXthatiwrote'
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