0
String = 'var1 = hello, var2 = bye'

So i have this string that is being returned from a webpage and im trying to turn this into this:

   var1 = 'Hello'
   var2 = 'bye'

I was wondering if this could be done using .format or something else.

one of my biggest problem is time, i want the fasted method.

  • 3
    I smell an [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). What are you trying to accomplish with this? – Julia Dec 31 '22 at 10:09
  • 1
    No, you do *not* want to create variable variables from a string, and no, `.format` won't get you anywhere near it. – deceze Dec 31 '22 at 10:17
  • @deceze is right, however he's not telling you that you CAN do that using f-strings and walrus. It's a bad practice for sure...but you CAN xD – Gameplay Dec 31 '22 at 10:18
  • @Gameplay Err, please clarify how f-strings and walruses help here? – deceze Dec 31 '22 at 10:20

1 Answers1

2

Use a dictionary to store key value pair

data = 'var1 = hello, var2 = bye' # the data returned from a web page

dmap = {}

for value in data.split(","):
    array = value.split("=")
    dmap[array[0].strip()] = array[1].strip()

print(dmap)
Udesh
  • 2,415
  • 2
  • 22
  • 32
  • 1
    FWIW, a one-liner: `d = dict(map(str.strip, i.split('=')) for i in data.split(','))`. – deceze Dec 31 '22 at 10:19
  • Except for the fact that `dmap` is pretty bad and non-descriptive name for anything it's all good – Gameplay Dec 31 '22 at 10:20
  • Forget my previous comment, the oneliner is way worse ‍♂️ I hope that during the code review that would get rejected. – Gameplay Dec 31 '22 at 10:22
  • 1
    @CoolGuy Please provide the `String` value on which you are working because the above expression is for `string` data in this particular format 'var1 = val1, var2 = val2, var3 = val3, varn = valn' – Udesh Jan 01 '23 at 00:49
  • @devp I apologies the problem I had was that there was a ``,`` at the start of my string which is why I got that error. Thank you for your respond and your answer. –  Jan 01 '23 at 00:54