简体   繁体   中英

How to extract specific variables from a string python?

I have a string like "A:22.0 /4.03 B:15.05 /3.0 C:120.15 /12.4" (with the spaces).


I want to extract the numbers and to store them intro variables with specific names. For the example, i want to have the variable A1 = 22.0 , A2 = 4.03 , B1 = 15.05 , B2 = 3.0 , C1 = 120.15 , C2 = 12.4
The variables in the string might not be in this order, but there will always be groups of:
(variable name):(value1) /(value2) in this order.

Any help or idea is appreciated. Thank you!

There are a million ways to do this. Regular expressions are great and can be helpful for missing values and other edge cases. Assuming your data is never missing a value or in any other format a simple string replacement and split can do the job.

You'll find it difficult name variables based on values from a string (A1, A2, etc). It's better to use a dictionary to store this type of data.

The complex part of this is the construction of the dictionary, which in this case is counting from 0 to the length of items in the split list, by 3s, and using those numbers to create the key:value pairs of the dictionary.

Original String

x = "A:22.0 /4.03 B:15.05 /3.0, C:120.15 /12.4"

Replace special characters w/space and split on spaces (will remove extra whitespace)

b = x.replace(':',' ').replace('/',' ').split()

Gives you

['A', '22.0', '4.03', 'B', '15.05', '3.0,', 'C', '120.15', '12.4']

Construct a dictionary from your data

output = {b[x]:[b[x+1],b[x+2]] for x in range(0,len(b),3)}

Output:

{'A': ['22.0', '4.03'], 'B': ['15.05', '3.0,'], 'C': ['120.15', '12.4']}

Then access the data as such:

output['A'][0]
22.0
output['A'][1]
4.03

To extract them, you should use Regex: here is the documentation: RegEx (Python)

But I recommend you to take a look at dictionaries. It will provide a control of keys and values, it looks what you need. Here is an example:

variableName = {
        "A1":22.0,
        "A2":4.03
    }

Here is the link to a good tutorial of how to use this: https://www.pythonforbeginners.com/dictionary/how-to-use-dictionaries-in-python/

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