Next / Previous / Contents / TCC Help System / NM Tech homepage

4.8. pythonizeName(): Sanitize an XML name for Python use

This function implements the various rules for converting an XML name.

pyrang
def pythonizeName(s):
    """Convert an XML name to its Python equivalent.
    """

The general approach will be to add the translated characters to a list named xlated. We start by creating this list empty.

pyrang
    #-- 1
    xlated = []

Next we work through the input string, adding each character's worth of content to the xlated list.

pyrang
    #-- 2
    # [ xlated  +:=  characters from s, convert to string type,
    #       uppercasing lowercase characters, adding "_" at each
    #       lowercase->uppercase transition, and converting "-"
    #       to "-" ]
    for i in range(len(s)):
        #-- 2 body
        # [ if s[i] == '-' ->
        #     xlated  +:=  ['_']
        #   else if s[i] is lowercase ->
        #     xlated  +:=  [str(s[i]), uppercased]
        #   else if (s[i] is uppercase) and (i>0) and
        #   (s[i-1] is lowercase) ->
        #     xlated  +:=  ["-", str(s[i])]
        #   else ->
        #     xlated  +:=  [str(s[i])] ]

        #-- 2.1
        c = str(s[i])

        #-- 2.2
        if  c == '-':
            xlated.append('_')
        elif  c.islower():
            xlated.append(c.upper())
        elif  c.isupper():
            if (( i > 0) and
                 (s[i-1].islower())):
                xlated.append('_')
            xlated.append(c)
        else:
            xlated.append(c)

The result is the concatenation of the elements of xlated.

pyrang
    #-- 3
    return  "".join(xlated)