Using .split(), I want save a string into 2 or 3 separate variables

Viewed 85

Lets assume I have this in the line line=vaddpd %ymm8,%ymm7,%ymm6

what I want is to get a=%ymm8, b=%ymm7, c=%ymm6

or lets say we have in the line line=cmp %rsi,%rbx

i want to get a=%rsi, b=%rbx

x=line.split(",")
3 Answers

Start with using split on the space:

line="vaddpd %ymm8,%ymm7,%ymm6"
split_list = line.split(" ")[1].split(",")

Then you have a list of your desired variables. You can assign them however you like, for instance a dictionary:

import string
keys = list(string.ascii_lowercase)
my_dict = dict(zip(keys, split_list))
import re

line = "vaddpd %ymm8,%ymm7,%ymm6"
splt_line = re.split(r"[ ,]", line)

After this, you can assign elements of splt_line to any variable you want.

Using the Python 3.10+ pattern matching seems both simpler and more robust than simple splits (which would throw IndexError on malformed data).

Kids, don't try this at home on a Python version lower than 3.10 => syntax errors

    def do_2or3(input_):
        print(f"\n\n{input_}:")
        
        match input_.split():
            case _, data:
                match data.split(","):
                    case a,b,c:
                        print(f"  {a=} {b=} {c=}")
                    case a,b:
                        print(f"  {a=} {b=}")
                    case _:
                        print(f"  !not a,b,c with {input_=}")
            case _:
                print(f"  !not a,b,c with {input_=}")


    do_2or3("line=vaddpd %ymm8,%ymm7,%ymm6")
    do_2or3("line=cmp %rsi,%rbx")
    do_2or3("line=cmp.%rsi,%rbx")
    do_2or3("line=cmp %rsi,%rbx,d,e")


output:




line=vaddpd %ymm8,%ymm7,%ymm6:
  a='%ymm8' b='%ymm7' c='%ymm6'


line=cmp %rsi,%rbx:
  a='%rsi' b='%rbx'


line=cmp.%rsi,%rbx:
  !not a,b,c with input_='line=cmp.%rsi,%rbx'


line=cmp %rsi,%rbx,d,e:
  !not a,b,c with input_='line=cmp %rsi,%rbx,d,e'


Related