Strings: Python snippets
Part of 30 Seconds of Python. Source: snippets/strings.py.
Every example below is run as a test.
words
Split text into words, understanding camelCase, snake_case and kebab-case.
def words(text):
return _WORDS.findall(text)
>>> words('parseHTTPResponse_code-v2')
['parse', 'HTTP', 'Response', 'code', 'v', '2']
snake_case
Convert any casing to snake_case.
def snake_case(text):
return '_'.join(w.lower() for w in words(text))
>>> snake_case('someHTTPRequest ID')
'some_http_request_id'
kebab_case
Convert any casing to kebab-case.
def kebab_case(text):
return '-'.join(w.lower() for w in words(text))
>>> kebab_case('Hello World_again')
'hello-world-again'
camel_case
Convert any casing to camelCase.
def camel_case(text):
ws = [w.lower() for w in words(text)]
return ws[0] + ''.join(w.capitalize() for w in ws[1:]) if ws else ''
>>> camel_case('user_id-from header')
'userIdFromHeader'
pascal_case
Convert any casing to PascalCase.
def pascal_case(text):
return ''.join(w.capitalize() for w in words(text))
>>> pascal_case('user_id')
'UserId'
slugify
URL-friendly slug: ASCII, lowercase, hyphen separated.
def slugify(text):
ascii_text = unicodedata.normalize('NFKD', text).encode('ascii', 'ignore').decode()
return re.sub(r'[^a-z0-9]+', '-', ascii_text.lower()).strip('-')
>>> slugify(' Crème Brûlée: 10 Recipes! ')
'creme-brulee-10-recipes'
truncate
Shorten text to at most length characters including the suffix.
def truncate(text, length, suffix='...'):
if len(text) <= length:
return text
return text[:max(0, length - len(suffix))] + suffix
>>> truncate('The quick brown fox', 10)
'The qui...'
>>> truncate('short', 10)
'short'
is_palindrome
Palindrome check that ignores case, spaces and punctuation.
def is_palindrome(text):
clean = [c.lower() for c in text if c.isalnum()]
return clean == clean[::-1]
>>> is_palindrome('A man, a plan, a canal: Panama')
True
is_anagram
True if two strings use the same letters (case and spaces ignored).
def is_anagram(a, b):
norm = lambda s: sorted(c.lower() for c in s if c.isalnum())
return norm(a) == norm(b)
>>> is_anagram('Dormitory', 'dirty room')
True
strip_accents
Remove diacritics: é -> e, ñ -> n.
def strip_accents(text):
return ''.join(c for c in unicodedata.normalize('NFKD', text) if not unicodedata.combining(c))
>>> strip_accents('Café señor')
'Cafe senor'
collapse_whitespace
Turn every run of whitespace into one space and trim the ends.
def collapse_whitespace(text):
return ' '.join(text.split())
>>> collapse_whitespace(' too many\n\tspaces ')
'too many spaces'
count_vowels
Count vowels (a, e, i, o, u), case-insensitive.
def count_vowels(text):
return sum(c in 'aeiou' for c in text.lower())
>>> count_vowels('Hello World')
3
mask
Hide all but the last visible characters.
def mask(text, visible=4, char='*'):
if visible <= 0:
return char * len(text)
return char * max(0, len(text) - visible) + text[-visible:]
>>> mask('4242424242424242')
'************4242'
wrap_lines
Hard-wrap text to width columns without breaking words.
def wrap_lines(text, width):
import textwrap
return textwrap.wrap(text, width)
>>> wrap_lines('one two three four five', 9)
['one two', 'three', 'four five']
remove_prefix_suffix
Strip one exact prefix and suffix if present (str.removeprefix/removesuffix).
def remove_prefix_suffix(text, prefix='', suffix=''):
return text.removeprefix(prefix).removesuffix(suffix)
>>> remove_prefix_suffix('test_utils.py', 'test_', '.py')
'utils'
human_bytes
Format a byte count for people.
def human_bytes(n, binary=True):
base = 1024 if binary else 1000
units = ['KiB', 'MiB', 'GiB', 'TiB', 'PiB'] if binary else ['kB', 'MB', 'GB', 'TB', 'PB']
if abs(n) < base:
return f'{n} B'
size = float(n)
for unit in units:
size /= base
if abs(size) < base or unit == units[-1]:
return f'{size:.1f} {unit}'
>>> human_bytes(1536)
'1.5 KiB'
>>> human_bytes(1_500_000, binary=False)
'1.5 MB'
>>> human_bytes(512)
'512 B'