Insert some string into given string at given index

Viewed 341357

I am newbie in Python facing a problem: How to insert some fields in already existing string?

For example, suppose I have read one line from any file which contains:

line = "Name Age Group Class Profession"

Now I have to insert 3rd Field(Group) 3 times more in the same line before Class field. It means the output line should be:

output_line = "Name Age Group Group Group Group Class Profession"

I can retrieve 3rd field easily (using split method), but please let me know the easiest way of inserting into the string?

9 Answers

Answer for Insert characters of string in other string al located positions

str1 = "ibuprofen"
str2 = "MEDICAL"
final_string=""
Value = 2
list2=[]
result=[str1[i:i+Value] for i in range(0, len(str1), Value)]
count = 0

for letter in result:
    if count < len(result)-1:
        final_string = letter + str2[count]
        list2.append(final_string)
    elif ((len(result)-1)==count):
        list2.append(letter + str2[count:len(str2)])
        break
    count += 1

print(''.join(list2))

Here's a simple function that extends on the above to allow inserting at an index or at any character within a string.

def insert(src, ins, at, occurrence=1, before=False):
    '''Insert character(s) into a string at a given location.
    if the character doesn't exist, the original string will be returned.

    :parameters:
        src (str) = The source string.
        ins (str) = The character(s) to insert.
        at (str)(int) = The index or char(s) to insert at.
        occurrence (int) = Valid only when 'at' is given as a string.
                    Specify which occurrence to insert at. default: first
        before (bool) = Valid only when 'at' is given as a string.
                    Specify inserting before or after. default: after
    :return:
        (str)
    '''
    try:
        return ''.join((src[:at], str(ins), src[at:]))

    except TypeError:
        i = src.replace(at, ' '*len(at), occurrence-1).find(at)
        return insert(src, str(ins), i if before else i+len(at)) if i!=-1 else src

#insert '88' before the second occurrence of 'bar'
print (insert('foo bar bar bar', 88, 'bar', 2, before=True))
#result:  "foo bar 88bar bar"
Related