0

If a string either follow this format such as 'a,b,c,d' (where a,b,c,d are all int) or completely empty. For example:

179,170,271,83
null
143,406,299,44
145,403,299,44
142,404,299,44

31,450,337,36

null

90,269,242,32
87,266,244,35
null
272,251,223,119
27,40,316,10

How can I store the value of a,b,c,d?

I tried using the split comma and check for empty string, but it doesn't help

if string:
      txt = string.split(',')
      height = txt[0]
      left = txt[1]
      top = txt[2]
      width = txt[3]
else:
      height = ""
      left = ""
      top = ""
      width = ""
martineau
  • 119,623
  • 25
  • 170
  • 301
Eric Jiang
  • 23
  • 4
  • How are you reading your input? Can you post examples for a non-empty string and an empty string from your input? – Unni Jun 10 '19 at 21:24
  • Do you really have empty lines and also lines containing the string `null`? – Barmar Jun 10 '19 at 21:45

2 Answers2

2

It's common in Python to use try/except in cases like this rather than testing first. This is often referred to as asking for forgiveness not permission. To do this you could wrap the expected case in the try and set edge case in the except:

def printDims(s):
    try:
        height, left, top, width = s.split(',')
    except ValueError:
         height, left, top, width = [''] * 4
    finally:
        print(height, left, top, width)


printDims("1,2,3,4") # prints 1, 2, 3, 4
printDims("")        # prints the empty strings
Mark
  • 90,562
  • 7
  • 108
  • 148
0

Check the length of txt:

if string:
    txt = string.split(',')
    if len(txt) == 4:
        height = txt[0]
        left = txt[1]
        top = txt[2]
        width = txt[3]
    else:
        height = ""
        left = ""
        top = ""
        width = ""
else:
    height = ""
    left = ""
    top = ""
    width = ""
martineau
  • 119,623
  • 25
  • 170
  • 301
Barmar
  • 741,623
  • 53
  • 500
  • 612