Python Basics #7 — Working with Strings
Welcome to lesson seven of the Python Basics series — working with strings.
What is a string? #
A string is a sequence of characters. You write a string by wrapping it in single or double quotes:
'string' or "string"You can join two strings with the + operator:
'schoolofweb' + '.net'Let’s see this in actual code:
>>> 'string'
'string'
>>> "string"
'string'Sometimes you need to include a quote character inside a string itself. The example below produces a syntax error:
>>> 'I'm a programmer'
File "<stdin>", line 1
'I'm a programmer'
^
SyntaxError: invalid syntaxTo include a single quote, wrap the string in double quotes; to include a double quote, wrap it in single quotes:
>>> "I'm a programmer"
"I'm a programmer"
>>> 'He says "Hello!"'
'He says "Hello!"'Another way is to escape special characters with a backslash. Let’s fix the previous example:
>>> 'I\\'m a programmer'
"I'm a programmer"Now it prints without an error.
To concatenate strings, use the + operator:
>>> 'schoolofweb' + '.' + 'net'
'schoolofweb.net'But if you want to concatenate a string and a number, you must convert the number to a string first. Let’s try concatenating a number with a string:
>>> 'I am ' + 18 + ' years old'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "int") to strA TypeError occurs.
Now let’s convert the number to a string and concatenate:
>>> 'I am ' + str(18) + ' years old'
'I am 18 years old'Now it concatenates without issues.
What is indexing? #
Indexing means using bracket syntax with a number to extract a specific character from a string. Python uses zero-based indexing, meaning indexes start from 0. So the first item has index 0, the second item has index 1, the third has index 2, and so on.

In the image above, given the string STRING, the first character S is the first item with index 0. As you move right, the index increases by 1.
Indexing from the last character is called reverse indexing, where the index starts at -1 and decreases by 1.
Let’s store STRING in a variable and print the first character S using its index:
>>> var = 'STRING'
>>> var[0]
'S'Now let’s use a reverse index to print the last character G:
>>> var[-1]
'G'The valid index range for this string is 0 to 5. Using an index outside that range raises an IndexError.
Python uses zero-based indexing — and so do most mainstream languages: C++, Java, JavaScript. Languages like Lua, Julia, and R use one-based indexing, where indexes start at 1.
Now let’s learn about slicing.
What is slicing? #
Slicing uses bracket syntax (like indexing) to extract a substring from a string. Indexing extracts a single character; slicing can extract multiple characters.
Slicing syntax takes three numbers inside brackets, separated by colons:
[start:stop:step]startis the index of the first character you want to extract.stopis the index one past the last character you want to extract.stepis the increment fromstarttostop.stepis optional; if omitted, it defaults to1.
To extract the first 3 characters of the example string, use [:3]:
>>> var[0:3]
'STR'When start is 0, you can omit it:
>>> var[:3]
'STR'To extract the last 3 characters, use [-3:]:
>>> var[-3:]
'ING'To extract the middle 2 characters, use [2:4] or [-4:-2]:
>>> var[2:4]
'RI'
>>> var[-4:-2]
'RI'Now let’s use a step to extract only the letters from a mixed numbers-and-letters string:
>>> mixed = '1a2b3c'
>>> mixed[1::2]
'abc'Now let’s look at some methods provided by the built-in str class.
str methods #
upper: convert the string to uppercaselower: convert the string to lowercasecapitalize: convert the first character to uppercasesplit: split the string into a list of itemsjoin: join other strings with a specified character or stringstrip: remove whitespacereplace: replace specific characters with other charactersformat: replace placeholders inside a string with provided values
In Python, everything is an object of some class, and you can use the methods defined on that class. The string class provides many handy methods.
Let’s use the most common ones.
First, store a sentence in a variable and check its type with the type function:
>>> greeting = 'welcome to schoolofweb.net.'
>>> type(greeting)
<class 'str'>Confirmed — it’s a string object.
Use dir to print all methods available on a string object:
>>> dir(greeting)
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'removeprefix', 'removesuffix', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']If you’re using IPython or Jupyter Notebook, you can press Tab to see code hints.

You can see all the available methods.
Use capitalize to convert the first character to uppercase:
>>> greeting.capitalize()
'Welcome to schoolofweb.net.'Use upper to make everything uppercase, and lower to make everything lowercase:
>>> greeting.upper()
'WELCOME TO SCHOOLOFWEB.NET.'
>>> greeting.lower()
'welcome to schoolofweb.net.'Use join to join characters using a specific separator:
>>> period = '.'
>>> abc = 'ABC'
>>> period.join(abc)
'A.B.C'Each character in ABC is now joined by a period.
Use strip to remove whitespace from both ends:
>>> spaces = ' strip example '
>>> spaces.strip()
'strip example'The whitespace on both sides is removed.
Use split to split a string by a separator (here, a comma):
>>> numbers = 'one,two,three,four,five'
>>> numbers.split(',')
['one', 'two', 'three', 'four', 'five']Each word is split by the comma into a list.
Use replace to substitute specific characters or substrings:
>>> foo = 'this is a java tutorial for java programmers'
>>> foo.replace('java', 'python')
'this is a python tutorial for python programmers'The string java was replaced with python.
String formatting #
Empty curly braces:
'My name is {}. I am {} years old.'.format(name, age)Keywords:
'My name is {name}. I am {age} years old.'.format(name=name, age=age)Indexes:
'My name is {1}. I am {0} years old.'.format(age, name)The last method we’ll cover is format. Using format, you can define multiple placeholders inside a string with curly braces and dynamically substitute them with values — think of it as a template.
To use format, define placeholders with curly braces inside the string. There are three ways to use them.
The first is empty curly braces. With empty braces, the arguments to format fill in the placeholders in order:
>>> name = 'Pink'
>>> age = 13
>>> 'My dog\\'s name is {}. She is {} years old.'.format(name, age)
"My dog's name is Pink. She is 13 years old."The number of placeholders must match the number of arguments. If they don’t match, an IndexError occurs. In the next example, there are 2 placeholders but only 1 argument:
>>> 'My dog\\'s name is {}. She is {} years old.'.format(name)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: Replacement index 1 out of range for positional args tupleThe second method is keywords. When you have many placeholders or reuse the same value multiple times, keywords are recommended:
>>> 'My dog\\'s name is {name}. She is {age} years old.'.format(name=name, age=age)
"My dog's name is Pink. She is 13 years old."The third method is indexes. Inside the curly braces, write the index of the argument passed to format:
>>> 'My dog\\'s name is {1}. She is {0} years old.'.format(age, name)
"My dog's name is Pink. She is 13 years old."You can also zero-pad numbers like this:
>>> for i in range(1, 11):
... print('file_{:03d}'.format(i))
...
file_001
file_002
file_003
file_004
file_005
file_006
file_007
file_008
file_009
file_010Here 0 means “fill empty space with the zero character” and 3 is the minimum width of the string.
You can also define decimal precision with format. Let’s print 3 decimal places:
>>> '{:.3f}'.format(1.55555)
'1.556'Note that truncating decimals rounds (up or down), not just chops.
When printing logs and similar output, you can align columns left, center, or right and pad widths to make output more readable:
>>> text = ''
>>> text += '{:10s} {:9s} {:4s}\\n'.format('First Name', 'Last Name', 'Age')
>>> text += '{} {} {}\\n'.format('-'*10, '-'*9, '-'*4)
>>> for person in people:
... text += '{:>10s} {:^9s} {:<4d}\\n'.format(person['firstname'], person['lastname'], person['age'])
...
>>> print(text.strip())
First Name Last Name Age
---------- --------- ----
John Doe 30
Jane Doe 29
Curtis Lee 43That wraps up this lesson. In the next lesson we’ll cover lists.