TAGS :Viewed: 9 - Published at: a few seconds ago

[ concatenating strings at particular position in Python ]

I have a string as:

string1 = '../data/annotation/product_Aca_ma_MBIC11017.txt'

It is basically a path for the file that I will use later.

I want to add string2 = 'fake_' to string1 at a particular position, to make it look like:

'../data/annotation/fake_product_Aca_ma_MBIC11017.txt'

So far, I did:

string1 = string2+string1

It outputs as:

'fake_../data/annotation/product_Aca_ma_MBIC11017.txt'

What should I do to add string2 at a particular position of string1?

Answer 1


You are manipulating paths, so use os.path to split and rejoin:

dir, filename = os.path.split(string1)
string1 = os.path.join(dir, string2 + filename)