Skip to content

Instantly share code, notes, and snippets.

@martinapugliese
Created August 12, 2016 11:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save martinapugliese/48d363776486a342508beb7717d1c00d to your computer and use it in GitHub Desktop.
Save martinapugliese/48d363776486a342508beb7717d1c00d to your computer and use it in GitHub Desktop.
Collection of examples of Python built-in methods for manipulating strings
# Copyright (C) 2016 Martina Pugliese
def run_methods():
print '\n'
print '* Count occurrences of substring in string'
print 'Martina'.count('art')
print 'Martina'.count('a')
print 'Martina'.count('a', 1, 3) # in slice of str (giving start/end)
print 'Martina'.count('a', 1) # in slice of str (givin only start)
print '* Find lowest index of substring in string'
print 'Martina'.find('a')
print 'Martina'.find('rt')
print 'Martina'.find('a', 2, 10) # start/end again
print 'Martina'.find('y') # -1 if not found
print '* Does str start/end with substring?'
print "I go".startswith('I'), "I go".startswith('I ')
print 'Martina'.endswith('na')
print '* Does str have some characteristics?'
print 'Martina'.isupper(), 'MART'.isupper()
print 'martina'.islower(), 'Ma'.islower()
print '123'.isdigit(), '1a'.isdigit()
print '1'.isalpha(), 'abc'.isalpha()
print '1a'.isalnum(), '&'.isalnum()
print ' '.isspace(), ' a'.isspace()
print 'Martina'.istitle(), 'martina'.istitle(), \
'mArtina'.istitle(), 'MARTINA'.istitle(), \
'Martina Goes'.istitle(), 'Martina goes'.istitle()
print '* Apply some transformations'
strg = 'maRtina goes' # transformations return a copy
print strg.lower(), strg.upper()
print strg.title()
print strg.swapcase()
print strg
print '* Stripping some chars'
print 'x Martinax'.lstrip('x ') # stripping from the left
print 'xwMartinax'.rstrip('xw') # stripping from the right
print 'xwMartinax'.strip('xw') # stripping both ways
print '* Separating in parts at separator'
print 'Martina'.partition('ar')
print '* Replacing'
print 'M art ina'.replace(' ', '')
print 'M\nartina'.replace('\n', '$')
print 'Martinaa'.replace('a', 'A', 2) # only the first num occurrences
print '* Splitting'
print 'Martina goes to school'.split()
print 'Martina goes to school'.split()
print 'Martina goes to school'.split(' ')
print 'Martina\nlikes\rschool.\r\nBla\nbla.'.splitlines()
print '* Joining'
print 'Martina'.join(['1', '2', '3'])
print 'Martina'.join(['bla'])
print 'Martina'.join('bla')
print '* Formatting'
print 'Martina {0} {1} and {2}'.format('eat', 'apple', 'sleep') # args
print 'Martina {verb1} {obj} and {verb2}'\
.format(verb1='eat', obj='apple', verb2='sleep') # kwargs
if __name__ == '__main__':
run_methods()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment