Aug. 25, 2021


Teacher Resources
...

Originally posted: Aug. 25, 2021
Last edited: 1 year ago


Strings in Python

In this lecture we will discuss strings and str type in Python, you will learn:

  • What are strings in Python
  • String basics
  • String indexing

What are strings in Python

Strings in Python are sequences of characters used to represent text information. A character is simply a symbol. For example, the English language has 26 characters. Strings are represented using the str type. Here are few facts about strings:

  1. Strings can be delimited by single or double quotes, as long as the same kind is used at both ends.

  2. An empty string is simply a string with nothing between the delimiters.

  3. In Python a character is a string of length 1.

For the next exercises you will be using our Python Compiler located in the Resources tab:

 

String basics

To create a string object in Python, simply put the text you want within single or double quotes.

 
print('hello world!')   #this is a string with single quote 
 
hello world!
 
print("hello world!")  #this is a string with double quotes 
 
hello world!
 

Strings are immutable

In Python, objects of type str or any basic numeric types such as int or float are immutable. Once the object is created and assigned a value, that value cannot be changed. We mention that because although we can use square brackets to retrieve the character at a given index position in a string (as we will see in the string indexing section), we cannot use them to set a new character, see the example below.

In this example, we have created an object of type string with the value 'Cat' and made the object reference animal refer to it. Now we want to change the character 't' at position 2 to be character 'n', but Python doesn't allow that. The error says "'str' object does not support item assignment", this means we cannot change the characters already assigned to that string object.

 
animal = 'Cat'
animal[2] = 'n'
 
---------------------------------------------------------------------------

TypeError: 'str' object does not support item assignment
 

However, we can create another string object and make animal refer to it. But the origianl object with value 'Cat' is still unchanged.

 
animal = 'Cat'
 

String length

As strings are sequences they are “sized” objects, therefore we can call len() function and pass a string as an argument to find the size (length) of that string.
The len() function will return the string length which is the number of characters in the string.

  • len() returns zero for an empty string.
 
print(len(''))               # an empty string is passed to len() function
 
0
 
print(len("Hello World"))    # this string has 11 characters (including spaces)
 
11
 
st = 'I have homework' # this string has 15 characters (including spaces)
print(len(st))
 
15
 

NOTE: spaces are also considered as characters and are counted by len() function.

 

String conversions

The built-in function str() in Python converts a data item such as an integer or float number to a string.

Check out the following examples:

 
print(int("10"))     # to covert a string '10' to an integer number 10
 
10
 
print(float("2.5"))  # to convert a string '2.5' to a floating-point number 2.5
 
2.5
 
print(str(10))       # to covert an integer number 10 to string '10'
 
'10'
 
print(str())         # if nothing passed to str(), the function returns an empty string
 
''
 
print(str('Python')) # if a string is passed to str(), the function returns a copy of that string
 
'Python'
 

GENERAL RULE:

To covert a data item from one type to another, use this syntax

                              datatype(item)
 
print("Hello! this is the first line \n then the second line")
 
Hello! this is the first line 
then the second line
 

Or to add some tabs to your string, use \t

 
print ("Hello! this is the first sentence \t then the second sentence")
 
Hello! this is the first sentence 	 then the second sentence
 

String indexing

Python uses square brackets [ ] to access an item in a sequence such as a string. The square brackets [ ] are also called the access operator. Suppose we are working in the Python Shell, interactive interpreter, or our Python Compiler. We can enter the following:

 
print("Hello There!"[4])
 
o
 
s = 'program'
print(s[0])
 
p
 

The square brackets syntax can be used with data items of any data type that is a sequence, such as strings and lists. This consistency of syntax is one of the reasons that Python is so beautiful.

NOTE: the number between the square brackets is called an index, all Python index positions start at 0 and ends at the string length minus 1.

Let's see the first and the last index in the following example.

The method index() is called for the string s just to show you the first and last index. Do not worry about the method right now, it will be covered in detail in another lecture, String Operators and Methods.

 
s = 'Hello World'
print(s.index('H'), s.index('d'), len(s))
 
0, 10, 11
 

Notice that the first index = 0, the last index = 10 and the length of the string s = 11

So, the last index = length - 1 = 11 - 1 = 10

 

In Python, index positions can be positive or negative.

  • positive index count from the first character toward the last.
  • negative index count from the last character back toward the first