简体   繁体   中英

How to extract specific characters from a string in Python?

say I have a string like this:

coordinates:x=22,y=45;x=144,y=56;x=26,y=13;x=144,y=87

and I want to store the values in 8 variables:

xCoord1 = 22
yCoord1 = 45
xCoord2 = 144
yCoord2 = 56
xCoord3 = 26
yCoord3 = 13
xCoord4 = 144
yCoord4 = 87

Note: coordinates could be 2 or 3 digits long only.

Better create a dictionary to hold the output.

You can use re.findall to extract the key/values and a dictionary comprehension to generate the output.

The auto incrementation of the keys can be done with a combination of collections.defaultdict and itertools.count

s = 'coordinates:x=22,y=45;x=144,y=56;x=26,y=13;x=144,y=87'

import re
from itertools import count
from collections import defaultdict

counter = defaultdict(lambda:count())

coords = {f'{k}Coord{next(counter[k])+1}': int(v)
          for k,v in re.findall('(\w+)=(\d+)', s)}

output:

{'xCoord1': 22,
 'yCoord1': 45,
 'xCoord2': 144,
 'yCoord2': 56,
 'xCoord3': 26,
 'yCoord3': 13,
 'xCoord4': 144,
 'yCoord4': 87}

Then access your values by selecting the coordinated by name:

>>> coords['xCoord1']
22
tuples as keys:

I would even prefer to use tuples as keys:

counter = defaultdict(lambda:count())
coords = {(k, next(counter[k])+1): int(v)
          for k,v in re.findall('(\w+)=(\d+)', s)}

coords['x', 1]
# 22

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