Python Strings

Python string is a sequence of characters. Examples of characters are letters (a, b, c etc), digits (1, 2, 3 etc), symbols ($, @, % etc) and even spaces.

Following are examples of valid strings:

"_underscrore"
"hello world!"
"$$$"
"100%"

You make a string by enclosing characters in matching single or double quotes.

>>> 'Python is cool'
'Python is cool'
>>> "just_do_it"
'just_do_it'

A number or other data types can be converted by using str() function.

>>> str(100)
'100'
>>> str(True)
'True'
>> str(10.9)
'10.9'

Common String operations

Combine one string with another

You can use ‘+’ to add one string to another. The ‘+’ operator works for both string literals and string variables.

>>> "Tomorrow " + "Never Dies"
'Tomorrow Never Dies'
>>> dob = "01/29/2005"
>>> "Amir was born on " + dob
'Amir was born on 01/29/2005'

Read characters from a string

As mentioned before, string is a sequence of characters. You can read characters from a string using an index within a square bracket. The first character is accessed using 0, the second character using 1 and so son. You can also use read from the right by using negative indices such as -1, -2, and -3.

>>> spider_man = "With Great Power, Comes Great Responsibility"
>>> spider_man[0]
'W'
>>> spider_man[10]
' '
>>> spider_man[11]
'P'
>>> spider_man[100]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: string index out of range
>>> spider_man[-1]
'y'
>>> spider_man[-2]
't'

Finding length of a string

You can find the length of a string using len() function.

>>> charlie_brown = "Keep looking up… that’s the secret of life."
>>> len(charlie_brown)
43

Getting part of a string

Often it is helpful to be able to get a portion of a string, which is known as “substring” by using a slice. Slice is defined by starting index and ending index inside a square bracket. Here are some common examples:

>>> quote = "be silly, be honest, be kind"
# display entire string
>>> quote[:]
'be silly, be honest, be kind'
# from index 10 to all the way end
>>> quote[10:]
'be honest, be kind'
# from index 2, till index 9, skipping characters by 2
>>> quote[2:10:2]
' il,'
# reverse the string
>>> quote[::-1]
'dnik eb ,tsenoh eb ,yllis eb'
# from the start till the index 19
>>> quote[:20]
'be silly, be honest,'
# last four characters
>>> quote[-4:]
'kind'

Splitting and joining

A string can be split into smaller strings or tokens using split() function. You can split by using any type of separator, including space.

>>> summer = "sun,sand,beach,movies"
# split by comma
>>> summer.split(',')
['sun', 'sand', 'beach', 'movies']
>>> winter = 'snow cold wind skiing'
# split by space
>>> winter.split()
['snow', 'cold', 'wind', 'skiing']

The opposite of split operation is join. Join operation is typically used on a list, which we haven’t discussed yet. For now, just assume that list is a collection of any data types. You can create list by simply using the following syntax.

>>> months = [ "Jan", "Feb", "Mar"]

The join() method is used to convert a list into a string, while optionally adding extra characters between each item in the list.

>>> fall = ['colors', 'leaves', 'raking']
# combine with "," between strings
>>> ', '.join(fall)
'colors, leaves, raking'
>>> months = [ "Jan", "Feb", "Mar"]
# combine with "|" between strings
>>> " | ".join(fall)
'colors | leaves | raking'

Changing case

There are several methods available to change the case of a string.

>>> quote = "when you know better, you do better"
# convert to upper case
>>> quote.upper()
'WHEN YOU KNOW BETTER, YOU DO BETTER'
# capitalize the first letter
>>> quote.capitalize()
'When you know better, you do better'
# capitalize all words
>>> quote.title()
'When You Know Better, You Do Better'
# convert to lower case
>>> quote.title().lower()
'when you know better, you do better'
# swap case
>>> quote = 'When You Know Better, You Do Better'
>>> quote.swapcase()
'wHEN yOU kNOW bETTER, yOU dO bETTER'

Formatting

Python allows formatting the output using different methods and we will focus on the newest style called f-strings. Here is an example:

>>> you = "You are"
>>> f'{you} amazing, {you} are important, {you} are unique, {you} are special'
'You are amazing, You are are important, You are are unique, You are are special'

You can do additional operations inside the format().

>>> f'{you} amazing, {you.upper()} are important, {you.upper()} are unique, {you.upper()} are special'
'You are amazing, YOU ARE are important, YOU ARE are unique, YOU ARE are special'

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *