4.4.1. 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.
4.4.1.1. A few things to know¶
Again, just a FEW basics.
concatenate two strings with ‘+’
you can slice strings like a list
a_str = 'Hey you' + ' there' # concatenate strings
a_str[3:5]
' y'
Use functions:
.split()
, takes a string and returns a list of strings, while.join()
takes a list and returns one string
a_str.split() #splits on spaces by default, notice the spaces are gone
['Hey', 'you', 'there']
a_str.split('e') # splits on the 'e's, notice the e's are gone
['H', 'y you th', 'r', '']
split_up = a_str.split()
# syntax: <string to use as joiner>.join(<list of strings>)
'---'.join(split_up)
'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:
a_str.replace('H','HHHH')
'HHHHey you there'