Home > OS >  .rsplit() | return empty string instead of `IndexError: list index out of range`
.rsplit() | return empty string instead of `IndexError: list index out of range`

Time:11-22

Instead of rsplit(), is there an alternative function that returns an empty string: "", and doesn't crash?

I want to return the "second-half" of a key's string, and place it at the end of its respective value's string. However, not always does a key have the ~ in its name.

If it doesn't have a "tag": ~tag, then I want to return an empty string.

Note: this might be easier without it being a dictionary-comprehension:

import random

DLM = '~'

programmatic_dict = {key: '{} {} {}'.format(val, DLM, key.rsplit(DLM, 1)[1]) if random.randint(0,9) == 9 else val for key, val in programmatic_dict.items()}  # 10% tag

Minimal Code: (resulting in the same error as the code above).

thisdict = {
  "brand~tag": "Ford",
  "model~tag": "Mustang",
  "year": 1964
}

DLM = '~'

for k in thisdict.keys():
    print(k.rsplit(DLM, 1)[1])

Output:

tag
tag
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-29-036aa5073b32> in <module>
      6 
      7 for k in thisdict.keys():
----> 8     print(k.rsplit(DLM, 1)[1])

IndexError: list index out of range

Please let me know if there is anything else I can add to post.

CodePudding user response:

If you really need the tag at hand, or, an empty string, write your own match function, preferably based on regex. Example:

import re

thisdict = {
  "brand~test": "Ford",
  "model~test": "Mustang",
  "year": 1964
}


r = re.compile(r". (~. )")


def my_match(k):
    m = r.match(k)
    if m:
        return m[1][1:]
    else:
        return ""


for k in thisdict.keys():
    print(my_match(k))
  • Related