Python String Processing Cheatsheet KDnuggets
Python String Processing Cheatsheet KDnuggets
Visit KDnuggets.com for more cheatsheets and additional Data Science, Machine Learning, AI & Analytics learning resources
Strip leading whitespace with lstrip(), trailing whitespace with Strings can be sliced like lists. Reversing one can be done in the Replace substrings with replace().
rstrip(), both with strip(). same way as a list's elements.
s1 = 'The theory of data science is of the utmost importance.'
s = ' A sentence with whitespace. \n' s = 'KDnuggets' s2 = 'practice'
>>> print('{}'.format(s.lstrip())) >>> print('The reverse of KDnuggets is {}'.format(s[::-1])) >>> print('{}'.format(s1.replace('theory', s2)))
The reverse of KDnuggets is: steggunDK The practice of data science is of the utmost importance.
>>> print('{}'.format(s.rstrip()))
>>> print('{}'.format(s.strip()))
Combining the Output of Multiple Lists
To strip characters other than whitespace, pass in the character(s) Converting Uppercase and Lowercase
you want stripped. Combine multiple lists in an element-wise fashion with zip().
Converting between cases can be done with upper(), lower(), and
>>> print('{}'.format(s.rstrip('A'))) swapcase(). countries = ['USA', 'Canada', 'UK', 'Australia']
cities = ['Washington', 'Ottawa', 'London', 'Canberra']
s = 'KDnuggets'
>>> for x, y in zip(countries, cities):
Splitting Strings >>> print(‘{}'.format(s.upper())) >>> print('The capital of {} is {}.'.format(x, y))
KDNUGGETS The capital of USA is Washington.
Split strings into lists of smaller substrings with split(). The capital of Canada is Ottawa.
>>> print('{}'.format(s.lower())) ...
kdnuggets
s = 'KDnuggets is a fantastic resource'
>>> print(‘{}'.format(s.swapcase()))
>>> print(s.split()) kdNUGGETS
['KDnuggets', 'is', 'a', 'fantastic', 'resource'] Checking for Anagrams
Other character(s) sequences can be passed. Check for anagrams by counting, comparing letter occurrences.