Subsequent to Changing second line text using ArcPy?, I want to know how can I change the fifth line from 'aaa' into 'plan b'

enter image description here

so the result will be:

enter image description here

with this code, by using index operator [5] and not with the solution of using the characters: '\n\n\n\n\n':

import arcpy
from arcpy import env

env.workspace = r"G:\desktop\Project"
for num, mxdname in enumerate((arcpy.ListFiles("*.mxd")),start = 1):
    print '\n',num,mxdname
    mxd = arcpy.mapping.MapDocument(
    r"G:\desktop\Project\\" + mxdname)
    for elm in arcpy.mapping.ListLayoutElements(mxd, "TEXT_ELEMENT"):
        elm.text = elm.text.replace(u'aaa', u'landUse')[5]
del mxd

but when i run it, I get an error:

Traceback (most recent call last):
  File "G:\desktop\y\test - עותק.py", line 10, in <module>
    elm.text = elm.text.replace(u'aaa', u'landUse')[5]
IndexError: string index out of range

A google on "python replace nth occurence of string" will take you here: Replace nth occurrence of substring in string and the accepted answer has a function for it:

def nth_repl(s, sub, repl, nth):
    find = s.find(sub)
    # if find is not p1 we have found at least one match for the substring
    i = find != -1
    # loop util we find the nth or we find no match
    while find != -1 and i != nth:
        # find + 1 means we start at the last match start index + 1
        find = s.find(sub, find + 1)
        i += 1
    # if i  is equal to nth we found nth matches so replace
    if i == nth:
        return s[:find]+repl+s[find + len(sub):]
    return s

a = "hello\nhello\nhello\nhello\nhello"
print(nth_repl(a, '\nhello', '\ngoodbye',3))

Or split into list, replace one element, join back to string:

a = "hello\nhello\nhello\nhello\nhello"
b = a.split('\n')
b[3] = 'goodbye'
a = "\n".join(b)
  • where i engage this function in my code? – newGIS May 12 at 9:47
  • I dont have ArcGIS on this computer so I cant try it but i think: elm.text = nth_repl(elm.text, '\nhello', '\ngoodbye',3) and the function definition after from arcpy import env – BERA May 12 at 10:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.