Top Rated Plus on Upwork with a 100% Job Success ScoreView on Upwork
retzdev logo
logo
tech

Common String Functions

by Jarrett Retz

December 11th, 2020

strings

One of the basic built-in data types in Python, a string, is a sequence of text characters. strings are declared with quotation marks:

  • single e.g 'string'
  • double e.g "string"
  • triple e.g """string""" '''string'''

You can also try to coerce other data types to be a string using the built-in str() function.

Strings are used all over the place in Python. Despite being so popular, a string in Python is immutable.

>>> example_str = 'string'
>>> example_str[1]
# 't'
>>> example_str[1] = "l"
# Traceback (most recent call last):
#  File "<pyshell#2>", line 1, in <module>
#    example_str[1] = "l"
# TypeError: 'str' object does not support item assignment

You can see, in the above code segment, that we can retrieve a value from a string using bracket notation. However, we can't directly reassign that value in the string. Hypothetically, this could negatively affect the flexibility of strings.

Thankfully, Python provides many functions that allow us to take control of strings and wield them like a powerful tool.

In this article, we are going to look at some of the common ways to manage and manipulate strings.

Basic Functions

Formatting

It's really convenient to format values inside a predefined string. Many times, we want to replace values in a sentence with dynamic values. The format() function has been a workhorse for Python developers because it does exactly that.

>>> print('My list: \n 1. {0} \n 2. {1}'.format('dishes', 'laundry'))
# My list: 
#  1. dishes 
#  2. laundry

Instead of numbering the values that we want to replace (i.e {0}, {1}), we could use keyword values.

>>> print('Hello {name}\n Your score is {score:.2f}'.format(name="Jarrett",score=4.05678))
# Hello Jarrett
#  Your score is 4.06

You may have noticed that I was also able to format the number and limit the decimals. There's much more you can do with the format() function. Check out the docs.

String Literals

I don't use the format() function very often. I mostly find myself using formatted string literals. It's similar, I think, to using template literals in Javascript.

>>> name = "Jarrett"
>>> score=4.056678
>>> print(f'Hello {name}\n Your score is {score:.3}')
# Hello Jarrett
#  Your score is 4.06

You can find useful examples for integer literals, numeric literals, string literals, and floating-point literals in the Literals documentation.

Split and Join

Strings are immutable, but lists are mutable. Therefore, it can be useful to split a string (returning a list) modify the items in the list, then reconnect the list (into a string) with join().

>>> column_list = "name address phone email".split(' ')
>>> column_list
# ['name', 'address', 'phone', 'email']
>>> for i in range(len(column_list)):
	column_list[i] = column_list[i].capitalize()
>>> ' '.join(column_list)
# 'Name Address Phone Email'

Another way to do this, that's easier, is "name address phone email".title()

Let's walk through this example. We have a string with column values and want each value to be capitalized.

First, we use split(' '), passing in a space, so the string is split into values divided by ' '.

Next, we iterate over the list and use another useful string function, capitalize(), to make the first letter of each item a capital letter.

Finally, we call join(column_list) on the string we want to join the items with. If we called join() on the string ', ' then each item would be combined with a comma followed by a space.

>>> ', '.join(column_list)
# Name, Address, Phone, Email'

Notice, we had to pass in the list for the argument.

Replace

The replace() function is golden. It will return the string placing the old value with the new value.

>>> british_words = "colour, flavour, honour"
>>> british_words.replace('ou', 'o')
# 'color, flavor, honor'

My example above does not give this function justice. It can be very effective when converting data. I use this function, frequently, when I'm working with the pandas​ library.

Other Common String Operations

The above functions are the string functions that I use the most. However, there many other functions that you can call on strings. To see a more comprehensive list, visit the string methods documentation.

.islower()

>>> "jarrett".islower()
# True
>>> "jaRrett".islower()
# False

.lower() .upper()

>>> "JOHN".lower()
# 'john'
>>> "hello!".upper()
# 'HELLO!'

.strip()

>>> '   strip            '.strip()
# 'strip'

.startswith()

>>> 'Mrs. Robinson'.startswith('Mrs.')
# True
Jarrett Retz

Jarrett Retz is a freelance web application developer and blogger based out of Spokane, WA.

jarrett@retz.dev

Subscribe to get instant updates

Contact

jarrett@retz.dev

Legal

Any code contained in the articles on this site is released under the MIT license. Copyright 2024. Jarrett Retz Tech Services L.L.C. All Rights Reserved.