#!/usr/bin/env python # coding: utf-8 # #Advanced Strings # String objects have a variety of methods we can use to save time and add functionality. Lets explore some of them in this lecture: # In[75]: s = 'hello world' # ##Changing case # We can use methods to capitalize the first word of a string, change cases to upper and lower case strings. # In[76]: # Capitalize first word in string s.capitalize() # In[77]: s.upper() # In[78]: s.lower() # ## Location and Counting # In[80]: s.count('o') # In[81]: s.find('o') # ##Formatting # The center() method allows you to place your string 'centered' between a provided string with a certain length. Personally, I've never actually used this in code as it seems pretty esoteric... # In[83]: s.center(20,'z') # expandtabs() will expand tab notations \t into spaces: # In[84]: 'hello\thi'.expandtabs() # ## is check methods # These various methods below check it the string is some case. Lets explore them: # In[40]: s = 'hello' # isalnum() will return True if all characters in S are alphanumeric # In[41]: s.isalnum() # isalpha() wil return True if all characters in S are alphabetic # In[43]: s.isalpha() # islower() will return True if all cased characters in S are lowercase and there is # at least one cased character in S, False otherwise. # In[44]: s.islower() # isspace() will return True if all characters in S are whitespace. # In[45]: s.isspace() # istitle() will return True if S is a title cased string and there is at least one character in S, i.e. uppercase characters may only follow uncased characters and lowercase characters only cased ones. Return False otherwise. # In[47]: s.istitle() # isupper() will return True if all cased characters in S are uppercase and there is # at least one cased character in S, False otherwise. # In[35]: s.isupper() # Another method is endswith() which is essentially the same as a boolean check on s[-1] # In[69]: s.endswith('o') # ## Built-in Reg. Expressions # Strings have some built-in methods that can resemble regular expression operations. # We can use split() to split the string at a certain element and return a list of the result. # We can use partition to return a tuple that includes the separator (the first occurrence) and the first half and the end half. # In[52]: s.split('e') # In[72]: s.partition('e') # In[58]: s # **Great! You should now feel comfortable using the variety of methods that are built-in string objects!**