Question

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

Était-ce utile?

La 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?

Autres conseils

stringvar_list= stringvar.split(';')
string_count = len(stringvar_list)

stringvar_list would then have the individual strings

newstr = stringvar.split(";")
n = len(newstr)
print "stringcount = " + str(n)
for i in range(n):
    print "string"+i+"="+str(newstr[i])
stringvar = "one;two,three;four"
l = stringvar.split(';')
stringcount, string1, string2, string3, string4 = len(l), l[0], l[1], l[2], l[3]

You should use split method

s = 'stringvar = "one;two,three;four"'
stringvar = s.split('=')[-1].strip()
L=stringvar.split(';')
stringcount=len(L)
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top