拆分和计算 Python 字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22101086/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Split and Count a Python String
提问by gomapping
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
谢谢
采纳答案by Adam Smith
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.
globals()返回一个字典,其中包含全局范围内的每个变量,变量名作为键的字符串,值作为值。
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 aequal 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 listinstead, shall we?
您可以参考此字典以按字符串名称添加新变量(globals()['a'] = 'b'将变量设置为a等于"b"),但这通常是一件很糟糕的事情。想想你怎么可能使用这些数据!您必须将新变量名称绑定到另一个变量,然后globals()[NEW_VARIABLE]每次都在内部使用它!让我们用 alist代替,好吗?
回答by Saeid
You should use splitmethod
你应该使用split方法
s = 'stringvar = "one;two,three;four"'
stringvar = s.split('=')[-1].strip()
L=stringvar.split(';')
stringcount=len(L)
回答by shaktimaan
stringvar_list= stringvar.split(';')
string_count = len(stringvar_list)
stringvar_listwould then have the individual strings
stringvar_list然后会有单独的字符串
回答by Vijay Kumar
newstr = stringvar.split(";")
n = len(newstr)
print "stringcount = " + str(n)
for i in range(n):
print "string"+i+"="+str(newstr[i])
回答by Raydel Miranda
stringvar = "one;two,three;four"
l = stringvar.split(';')
stringcount, string1, string2, string3, string4 = len(l), l[0], l[1], l[2], l[3]

