Home > front end >  How to get some values from a special set?
How to get some values from a special set?

Time:05-10

I need to get the rank number from this set:

{'rank': 'a=1;b=2;c=3', 'type': 'valid', 'name': 'Mr.A'}

I can get the rank value by this:

a = {'value': 'rank:a=1;b=2;c=3', 'type': 'valid', 'name': 'Mr.A'}
rank = a['value']
print(rank)

And I will get:

rank:a=1;b=2;c=3

How can I get the number from rank?

I want to split this by ';' and hope output the data like:

1,2,3

CodePudding user response:

Assuming the format doesn't change, first split by :, and take right part:

rank_value = rank.split(':')[1]

Then split by ;, and split each part by =, putting them in a list:

ranks = [x.split('=')[1] for x in rank_value.split(';')] 

Then you can join ranks to a single string:

','.join(ranks)

CodePudding user response:

You could use re.findall to isolate each number in the rank string:

a = {'value':'rank:a=1;b=2;c=3','type':'valid','name':'Mr.A'}
rank = a['value']
nums = ','.join(re.findall(r'\d ', rank))
print(nums)  # 1,2,3

CodePudding user response:

If the variable a['value'] is always formatted the same, you can use a list comprehension with isdigit() function :

rank = ','.join([i for i in a['value'] if i.isdigit()])

# Output
'1,2,3'
  • Related