Home > OS >  key,value - how to handle null - python
key,value - how to handle null - python

Time:03-03

My data is as below:

To: [email protected];[email protected]
CC: [email protected];[email protected]
BCC:

I am doing a key value split as below.

key, value = line.split(": ")

the issue is, it is not able to handle the null value for BCC.I get the below error

ValueError: not enough values to unpack (expected 2, got 1)

I was wondering what is the best way to handle null while using the key value split?

CodePudding user response:

You should include a check on the size before you perform unpacking if you don't know its size in advance.

data = """To: [email protected];[email protected]
CC: [email protected];[email protected]
BCC:"""

for line in data.split("\n"):
    result = line.split(": ")
    if len(result) == 2:
        [key, value] = result
        print(key, value)
    else:
        print("No emails found.")

prints

To [email protected];[email protected]
CC [email protected];[email protected]
No emails found.

CodePudding user response:

Instead of str.split(), use str.partition(). It always returns a 3-tuple of the text before the separator, the separator, and the text after the separator. If the separator is not found, there's no error raised, but the whole original string is in the first item, and the second and third items are empty strings.

key, _, value = line.partition(": ")
if not value:    # separator was not found
    print("no emails found")

CodePudding user response:

Please use the built in email parser

from email.parser import Parser

p = Parser()

data = """To: [email protected];[email protected]
CC: [email protected];[email protected]
BCC:"""

parsed = p.parsestr(data)

bcc = [e for e in parsed.get('BCC').strip().split(';') if not len(e) == 0]
print(
  'To:', parsed['To'].split(';'),
  '\nCC:', parsed['CC'].split(';'),
  '\nBCC', 'None' if not bcc else bcc
)

CodePudding user response:

When the code doesn't find the string you passed in split, it returns an array with one item. That is why it cannot unpack two values.

Fixed code:

split_line = line.split(": ")
if len(split_line) > 1:
    key, value = line.split(": ")
  • Related