Search code examples
pythonstringparameter-passing

Python passing & concatenating global string values


I have 4 global variables: mdstring, rxstring, dnstring, vsstring

I've verified the functions that set their values return strings (e.g. vsstring = "1|Vision|~Included with Medical.")

I have a dictionary that sets the order the strings will be used:

ordered_back_addreses = {
    #snip
    "5117": ordered_addr_string(mdstring, rxstring, dnstring, vsstring),
    #snip
}

And this is the function that is calling:

def ordered_addr_string(*addresses):
    global mdstring, rxstring, dnstring, vsstring
    ordered_addreses = ""
    for address in addresses:
        print(address)
        if address != "":
            #ordered_addreses = ordered_addreses + "^" + address
            pass
    return ordered_addreses

The commented line is what I'm trying to do. There might be 0 or more non-empty strings reference by those global variables. If the value is not an empty string, I want to add it to a ^ delimited new string, in the order specified. Also "5117" uses the four global names listed, but another key might use more or fewer.

The print(address) is showing me "object.Class object at address", so I think somehow I'm using names where I want values.

I've tried wrapping the variables in str() in the dictionary and in the function, and also I added the "global..." line at the start of the function, though I don't know if it was necessary and it didn't help.


Solution

  • The global references are unnecessary. All the data is already in addresses. If all you are trying to do is join them by "^", python has a built-in just for that. The below is all you need to accomplish your needs.

    def ordered_addr_string(*addresses):
        return '^'.join(address for address in addresses if address)
    

    I see an issue here, though. By eliminating empty values, they will no longer be in order and you will have absolutely no way to determine which value belongs to which variable. It's probably better to keep empty values. In which case you can just do this:

    "5117": '^'.join((mdstring, rxstring, dnstring, vsstring)),
    

    If you don't like potentially ending up with this: "^^something^something_else"

    You can go back to the function approach and do the below instead. If address is empty it will be replaced with the word "none".

    def ordered_addr_string(*addresses):
        return '^'.join(address or 'none' for address in addresses)