0% found this document useful (0 votes)
3 views

Python String Processing Cheatsheet KDnuggets

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Python String Processing Cheatsheet KDnuggets

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

Python String Processing Cheatsheet

Visit KDnuggets.com for more cheatsheets and additional Data Science, Machine Learning, AI & Analytics learning resources

Stripping Whitespace Reversing a String Replacing Substrings

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.

s = 'these,words,are,separated,by,comma' Checking for String Membership from collections import Counter


def is_anagram(s1, s2):
>>> print(‘{}’.format(s.split(','))) return Counter(s1) == Counter(s2)
Check for string membership using the in operator.
['these', 'words', 'are', 'separated', 'by', 'comma']
s1 = 'perpendicular' >>> print('listen is an anagram of silent ->
s2 = 'pen' {}'.format(is_anagram(‘listen’, ‘silent’)))
s3 = 'pep' listen is an anagram of silent -> True
Joining List Elements Into a String
>>> print('\'pen\' in \'perpendicular\': {}'.format(s2 in s1))
Join list element strings into single string in Python using join(). 'pen' in 'perpendicular': True
Checking for Palindromes
s = ['KDnuggets', 'is', 'a', 'fantastic', 'resource'] >>> print('\'pep\' in \'perpendicular\': {}'.format(s3 in s1))
'pep' in 'perpendicular': False Check for palindromes by reversing a word and then using ==.
>>> print(‘ '.join(s))
KDnuggets is a fantastic resource Find the location of a substring with find() (-1 means not present). def is_palindrome(s):
reverse = s[::-1]
Join list elements with something other than whitespace in s = 'Does this string contain a substring?' if (s == reverse):
between (“and” in this example). return True
>>> print('\'string\' location -> {}'.format(s.find('string'))) return False
s = ['Eleven', 'Mike', 'Dustin', 'Lucas', 'Will'] 'string' location -> 10
>>> print('racecar is a palindrome ->
>>> print(' and '.join(s)) >>> print('\'spring\' location -> {}'.format(s.find('spring'))) {}'.format(is_palindrome(‘racecar’)))
Eleven and Mike and Dustin and Lucas and Will 'spring' location -> -1 racecar is a palindrome -> True

Matthew Mayo, 2022

You might also like