简体   繁体   中英

extract python string into variables

In python, I have defined this sql string:

sqlstring=''
for i in range(1001):
    sqlstring+="dz"+str(i)+"\n"

I want to extract variables from this string.

so sql string contains :

dz0
dz1 
dz2 
dz3
dz4...

I want to have dz1 as one variable, how can i do that?

How about that you store those in a list and access them by index :

>>>sqllist = ['dz{}'.format(i) for i in range(1001)]
>>>sqllist[0]
dz0
>>>sqlist[1]
dz1

If you have 1000 variables that have those names you can access them with:

>>>eval(sqllist[0])
'something stored in dz0'
sqlstring='dz1 dz2 dz3 dz4 dz5'
datalist=[]
newsqlstring=sqlstring.split()
for each in newsqlstring:
    datalist+=[each]
print datalist

or if you want to create these use a list instead of string

sqlstring=[]
for i in range(1001):
    sqlstring+=["dz"+str(i)+"\n"]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM