Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert a string before a substring of a string

Tags:

python

string

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?

like image 314
user2378481 Avatar asked May 14 '15 08:05

user2378481


People also ask

How do you add strings before strings?

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.

How do you insert a string in Python?

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.

How do you add a string to a specific position in Python?

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.


1 Answers

Why not use replace?

my_str = "thisissometextthatiwrote"
substr = "text"
inserttxt = "XX"

my_str.replace(substr, substr + inserttxt)
# 'thisissometextXXthatiwrote'
like image 81
santon Avatar answered Oct 27 '22 19:10

santon