Skip to content

Commit

Permalink
nym: Expand usability
Browse files Browse the repository at this point in the history
This expands the number of translations and enables the
caller to (optionally) override the default translations.
  • Loading branch information
lhh authored and jpichon committed Apr 4, 2024
1 parent 6c2486b commit 61fbed2
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 4 deletions.
27 changes: 27 additions & 0 deletions tests/test_strutil_nym.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@

def test_identity():
assert nym('abc') == 'abc'
assert nym('') == ''
assert nym(None) is None


def test_spaces():
Expand All @@ -19,3 +21,28 @@ def test_tabs():

def test_lowercase():
assert nym('aBcDeF') == 'abcdef'


def test_underscores():
assert nym('a.b') == 'a_b'
assert nym('a-b+c') == 'a_b_c'


def test_removes():
assert nym('a(b)[c]{d}/e=f') == 'abcdef'


def test_non_null():
# If we pass in a string, we should get _something_ back,
# even if all characters would otherwise be removed
assert nym('()')


def test_integer():
assert nym(1) == '1'


def test_params():
assert nym('1', remove='1') == '_'
assert nym('12', underscore='1') == '_2'
assert nym('123', underscore='1', remove='3') == '_2'
13 changes: 9 additions & 4 deletions toolchest/strutil.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ def regex_match(pattern, arg):
return False


def nym(arg):
def nym(arg, underscore='+-. !?;:\'",\t', remove='()[]{}?<>/='):
'''
This is for allowing case and quote flexibility for strings when
searching dictionaries or other data sets based on user input (esp.
Expand All @@ -44,10 +44,15 @@ def nym(arg):
Parameters:
arg (string): A string to create the nym for
underscore (string): A set of characters to replace with underscores
remove (string): A set of characters to remove from the return value
Returns:
ret (string): A lower-case string with whitespace swapped to _
ret (string): A lower-case string with characters translated
or removed.
'''
ret = arg.lower().replace(' ', '_')
ret = ret.replace('\t', '_')
if (ret := arg) not in ('', None):
tr = str.maketrans(underscore, '_' * len(underscore), remove)
ret = str(arg).lower().translate(tr) or '_'

return ret

0 comments on commit 61fbed2

Please sign in to comment.