Search code examples
pythonstringcharacterincrementmove

find specific elements in string/list and move them by increment


I try to change the path in an SVG from cm to mm units. The path is defined by the string "d" and looks like this:

<path d="M317.3962167,-142.7 L317.3962167,-142.7 ...

I now want to move all the decimal points by an increment i (for cm to mm -> i=1). The result should look like:

<path d="M3173.962167,-1427 L3173.962167,-1427

or

<path d="M3173.962167,-1427.0 L3173.962167,-1427.0

so if the decimal point is moved and the following list entry is empty either the decimal point should then be erased or a "0" would need to be added. whatever is easier. I assume that first moving all decimal points and then erasing the points which are followed by an empty space in a second loop is the best option.

What I've got so far:

def cm_to_mm(chars, char, increment):
# Convert character sequence to list type.
char_list = list(chars)
if "." in chars:
    # Get the current index of the target character.
    old_index = char_list.index(char)
    # Remove the target character from the character list.
    char = char_list.pop(old_index)
    # Insert target character at a new location.
    new_index = old_index + increment
    char_list.insert(new_index, char)
    # Convert character list back to str type and return.
return ''.join(char_list)

But this moves only the first occurance of "."

I checked a lot of posts already but most are only talking about moving a character to the end with "append", which is not helping in my case. Thanks for your help, it's really appreciated!


Solution

  • You can use regex. You can save to manage string positions.

    import re
    
    def rpl(mo): 
        v= float(mo[0])*10 
        return str(v) 
    
    s= '<path d="M317.3962167,-142.7 L317.3962167,-142.7" >'
    
    re.sub(r"[-]?\d+[\.]?\d*",rpl,s)  
    
    '<path d="M3173.962167,-1427.0 L3173.962167,-1427.0" >'
    

    In re.sub the r"[-]?\d+[\.]?\d*" is the pattern of the float, rpl is a routin with match object as argument, m[0] is the first match, i.e. the float.