Try95th

alterTextVals

Nov 17th, 2022 (edited)
174
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.76 KB | None | 0 0
  1. ## for applying the same modification to all strings in nested iterables ##
  2. ## sample usage at https://pastebin.com/SGQN5pYd (part of a bigger solution)
  3.  
  4. def alterTextVals(val_to_alter, a, v):
  5.     if type(val_to_alter) in [list, tuple, set]:
  6.         pt = type(val_to_alter)
  7.         al = [alterTextVals(vta, a, v) if type(vta) in [
  8.             str, list, tuple, set # add any iterable class/type
  9.         ] else vta for vta in val_to_alter]
  10.         return al if pt == list else (set(al) if pt == set else tuple(al))
  11.    
  12.     detVal, a = str(val_to_alter), str(a)
  13.     if a == 'split': detVal = detVal.split(v)
  14.     elif a == 'word1': detVal = detVal.split(v)[0]
  15.     elif a == 'replace' and v and type(v) == tuple:
  16.         if len(v) == 1: detVal = detVal.replace(v[0], '')
  17.         elif len(v) == 2:
  18.             if type(v[1]) != int: detVal = detVal.replace(v[0], v[1])
  19.             else: detVal = detVal.replace(v[0], '', v[1])
  20.         else: detVal = detVal.replace(v[0], v[1], v[2])
  21.     elif a == 'elimWhite': detVal = v.join([w for w in detVal.split() if w])
  22.     elif a.startswith('truncate'):
  23.         v = v if type(v) == int and v > 10 else 10
  24.         a = a.replace('truncate', '', 1)[:5]
  25.         detVal = detVal[:(v - len(a))] + (a if len(detVal) > v else '')
  26.     elif a.startswith('truncSplit'):
  27.         a = a.replace('truncSplit', '', 1)[:5]
  28.         v = v if type(v) == int and v > 15 else 15
  29.         if len(detVal) > v:
  30.             v = (int(v - int((v - len(a))/2)), -1*int((v - len(a))/2))
  31.             detVal = detVal[:v[0]] + a + detVal[v[1]:]
  32.     elif a == 'prefix': detVal = f'{v}{detVal}'
  33.     elif a == 'suffix': detVal = f'{detVal}{v}'
  34.     # elif # can add more modifiers
  35.     else: detVal = a.join(detVal.split(str(v))) # default
  36.     return detVal
  37.  
Advertisement
Add Comment
Please, Sign In to add comment