Working with Python Strings

Python handles string objects powerfully and elegantly. There are a LOT of great tutorials and walkthroughs online, so I'm not going to replicate them. I'll list what I think are the barebones stuff here, and a few resources for you to reference.

A few things to know

Again, just a FEW basics.

  • concatenate two strings with '+'
  • you can slice strings like a list
In [1]:
a_str = 'Hey you' + ' there' # concatenate strings
a_str[3:5]
Out[1]:
' y'
  • Use functions: .split(), takes a string and returns a list of strings, while .join() takes a list and returns one string
In [2]:
a_str.split() #splits on spaces by default
Out[2]:
['Hey', 'you', 'there']
In [3]:
a_str.split('e')
Out[3]:
['H', 'y you th', 'r', '']
In [4]:
split_up = a_str.split()
# syntax: <string to use as joiner>.join(<list of strings>)
'---'.join(split_up)  
Out[4]:
'Hey---you---there'
  • You can wrap strings in ', ", ''', or """

    • If your string has ' or " inside it, use the opposite quotation type as the wrapper
    • ''' will let you use both internally, and the string can spill over multiple lines (like the doc string inside the functions in the community codebook folder)
  • You can use .replace() to replace characters:

In [5]:
a_str.replace('H','HHHH')
Out[5]:
'HHHHey you there'