9 Python String Operations to Memorize

Henry Rossiter
2 min readMay 27, 2020

The following functions and operators are used to manipulate strings in Python 3.

membership operator

The ‘in’ operator can be used to check if a substring exists in a string.

'hell' in 'hello' # True
'i' in 'team' # False
'a' not in 'the quick brown fox' # True

slicing

Much like lists, strings are slicable. String slicing can be used to select substrings or reverse strings.

s = 'I hate hamburgers'
s[:10] # 'I hate ham'
s[::-1] # 'sregrubmah etah I'
s[-1] # 's'

strip

The strip() method removes characters from both left and right based on the argument provided. If no argument is provided, leading and trailing white-spaces are removed.

s = ' boom '
s.strip() # 'boom'
s = 'ssssshhhh'
s.strip('s') # 'hhhh'

startswith

The startswith() method returns a boolean indicating whether the string starts with a given substring.

s = 'my mom'
t = 'my dad'
s.startswith('my m') # True
t.startswith('my m') # False

endswith

The endswith() method returns a boolean indicating whether the string ends with a given substring.

s = 'my mom'
t = 'my dad'
s.endswith('dad') # False
t.endswith('dad') # True

split

The split() method divides a sting into a list of substrings. If no argument is provided, white-spaces are used to divide the string. If an argument is provided, it is used to split up the string.

s = 'hi names dave really nice to meet'
s.split() # ['hi', 'names', 'dave', 'really', 'nice', 'to', 'meet']
s.split('dave') # ['hi names ', ' really nice to meet']

join

The join() method joins a list of strings into a single string. The string used to call the method is placed between every item in the list argument.

l = ['h', 'e', 'll', 'o']
''.join(l) # 'hello'
'-'.join(l) # 'h-e-ll-o'

lower

The lower() method converts all letters in a string to lower case.

s = 'Jungle BEATS'
s.lower() # 'jungle beats'

format

The format() method inserts the specified values inside the string's placeholders. The placeholders are defined using curly brackets: {}. Additional parameters can be used to specify the order and format of the arguments.

s = 'Hi {}, my name is {}.'
s.format('Hank', 'Henry') # 'Hi Hank, my name is Henry.'

--

--