Search code examples
pythonarcpy

Split and Count a Python String


So I have a string:

stringvar = "one;two;three;four"

I want to turn that into:

stringcount = 4
string1 = "one"
string2 = "two"
string3 = "three"
string4 = "four"

Sometimes there will be more sometimes less and of course the values could be whatever. I am looking to split a string at the ';' into separate variables and then have another variable that gives the number of variables.

thanks


Solution

  • NEVER DO THIS.

    Okay, now that we have that out of the way, here's how you do that.

    stringvar = "one;two;three;four"
    
    lst = stringvar.split(";")
    stringcount = len(lst)
    
    for idx, value in enumerate(lst):
        globals()["string"+str(idx+1)] = value
        # This is the ugliest code I've ever had to write
        # please never do this. Please never ever do this.
    

    globals() returns a dictionary containing every variable in the global scope with the variable name as a string for keys and the value as, well, values.

    For instance:

    >>> foo = "bar"
    >>> baz = "eggs"
    >>> spam = "have fun stormin' the castle"
    >>> globals()
    {'baz': 'eggs', '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__builtins__': <module 'builtins' (built-in)>, 'foo': 'bar', '__doc__': None, '__package__': None, 'spam': "have fun stormin' the castle", '__name__': '__main__'}
    

    You can reference this dictionary to add new variables by string name (globals()['a'] = 'b' sets variable a equal to "b"), but this is generally a terrible thing to do. Think of how you could possibly USE this data! You'd have to bind the new variable name to ANOTHER variable, then use that inside globals()[NEW_VARIABLE] every time! Let's use a list instead, shall we?