0

Say I have to split multiple strings within a for loop, which is separated with different delimiters. For example, here in the following example, I have . and - as delimiters.

I wanna split the strings and use the first part of the string. The example strings look like this,

ASD-2.T-bR.r1-v1_0
VXD.T-bR.r1-v1_0
VSR.T_bR_r1v1.0
SAP-LT_bR_r1v1.0

From the strings I need the string before the first . and - delimiters. I tried using,

for sam, keys in samp_dic.items():
        print(lab_key.split('.-',1)[0])

All the strings are values in a dictionary. The expected output is,

ASD
VXD
VSR
SAP

PS: The marked question (Split string with multiple delimiters in Python [duplicate] ) is for strings, my question is based on strings within dictionary

ARJ
  • 2,021
  • 4
  • 27
  • 52
  • I have edited my question now, with expected output – ARJ Sep 10 '19 at 09:11
  • 1
    `print([re.split(r"\.|-", s, 1)[0] for s in data.splitlines()])` – Olvin Roght Sep 10 '19 at 09:12
  • You can use regex with `(?<=\n|^)([^-.]+)` (assuming multiple lines) or `(?<=^)([^-.]+)` only work with first line – brazoayeye Sep 10 '19 at 10:36
  • Actually, `re.split` will not work on a dictionary – ARJ Sep 10 '19 at 11:45
  • @OlvinRoght, The `regular expression` solution throws error as the data is a dictionary – ARJ Sep 10 '19 at 11:47
  • @user1017373 replace `data.splitlines()` with `data.values()` or `data,keys()`. – Olvin Roght Sep 10 '19 at 11:48
  • @OlvinRoght, I tried both, Firstly, `[re.split(r"\.|-", s, 1)[0] for s,lab in samp_dic.keys().splitlines()]` then, it threw the same error, `AttributeError: 'dict_keys' object has no attribute 'splitlines'`. Secondly, if you completely replace like this: `[re.split(r"\.|-", s, 1)[0] for s,lab in samp_dic.keys()]`. Then it throws: `ValueError: too many values to unpack (expected 2)` – ARJ Sep 10 '19 at 11:50
  • @user1017373 you don't understand what are you doing. Correct way is `print([re.split(r"\.|-", s, 1)[0] for s in data.values()])`. – Olvin Roght Sep 10 '19 at 11:54

0 Answers0