Table of Contents[Hide][Show]
Welcome to the third lecture in the crash course.
In this lecture, we will learn to deal with strings in Python. Get your popcorn ready and sit tightly.
Strings
First, let’s talk about quotes and eliminate the confusion they might introduce in Python.
As stated before, we can use both single and double quotes after a function in Python. There is a specific utility of this. Suppose you want to print something like this.
print('This is Shahbaz's computer')
Now in the above expression, everything after the second quote as in “Shahbaz’s” will go unidentified by the python interpreter because Python will take the second quote as the end of the string. In that case, you wanna use the double quotes to declare the string like this:
print("This is Shahbaz's computer")
This can also be applied the other way round and we can use single quotes if there are double quotations inside the string. e.g.
print('This "computer" belongs to Shahbaz')
Now if you want to print a string that spans multiple lines, you would have to use triple quotes to enclose the string. These quotes can also be single or double depending upon the content of the string. For example:
Now let’s say you want to print a particular character from the string. How would you do that?
The Python interpreter indexes the characters in the string like this:
As you can see in the terminal, only ‘h’ has been printed. That’s because we have selected only the third character in our string to print on the terminal by writing 3 in square brackets write after the variable. The Python interpreter also indexes the characters in negative to simplify large strings. That means the ‘-1’ will be the last number in the string and so on. Note that the spaces are not indexed which means the above string will only have 21 indexed spaces.
You can also select a series of characters from the string. e.g.
HashDork = ('Python Course by Shahbaz')
print(HashDork[0:3])
This program will print ‘Pyt’ on the terminal. Index 3 is excluded from this.
HashDork = ('Python Course by Shahbaz')
print(HashDork[2:])
In the same manner, if we do not supply the end index, the python will print the whole string after the first index. The output of this program will be ‘thon Course by Shahbaz’. This holds vice versa. i.e. if we miss the first index then the whole string from the start to the last defined index will be printed.
A program with only the colon in the indexing brackets will yield the complete string on the terminal.
Excercise
Here is an interesting exercise
write a program that defines the index interval of [1:-1]. What do you think will be the output. Try it yourself.
Formatted Strings
Formatted strings are particularly useful in situations where you dynamically generate some text with your variables. Let me show you.
Let’s say we have two variables, first name, and last name.
first_name = 'Shahbaz'
last_name = 'Bhatti'
Now we want to print ‘Shahbaz [Bhatti] is a coder’ on the terminal. How would we do that? We will introduce a third variable like this:
message = 'first_name + ' [' + last_name + '] is a coder'
Now if we print and run this program, we will get ‘Shahbaz [Bhatti] is a coder’ on the terminal.
While this approach perfectly works, it’s not ideal because as our text gets more complicated it becomes harder to visualize the output. This is where we use formatted strings, they make it easier for us to visualize the output.
Let’s alter the third variable ‘message’ and introduce a formatted string. To define formatted strings, prefix your strings with an ‘ f ‘ and then use curly braces to dynamically insert values into your strings. Our program will look something like this:
first_name = 'Shahbaz'
last_name = 'Bhatti'
message = f'{first_name} [{last_name}] is a coder'
To define formatted strings, prefix your strings with an F and then use curly braces to dynamically insert values into your strings.
Cool things You can do with Python Strings
I’m going to show you some really cool things you can do with Python strings.
1. Number of Characters in a String
So let’s start by defining a variable:
message = 'Shahbaz Bhatti is a Coder '
Now if I want to determine the number of characters in the above string, there is a built-in function ” len ” in Python. Just print the variable with this function like this
print(len(message))
This is particularly useful when you receive input from the user. For example, you have noticed that when you fill out a form online, each input field often has a limit. For example, you might have 50 characters for your name, so using this ” len” function we can enforce a limit on the number of characters in an input field.
2. Converting Characters in a String to Uppercase or Lowercase
We can access the string-related functions through the dot operator. You can type your variable name and by putting a dot in front of it, you can see the list of all such functions.
Now in more accurate terms, you refer to these functions as methods, this is a term in object-oriented programming that we want to look at in the future, but for now, what I want you to take away, is that when a function belongs to something else or is specific to some kind of object, we refer to that function as a method. In this case, we will use the method “upper” for converting the string into uppercase.
As this function is specific to a string, we refer to this as a method. In contrast “len” and “print” are general-purpose functions, they don’t belong to strings or numbers or other kinds of objects. This is the basic difference between a function and a method.
Now, let’s print this.
message = 'Shahbaz Bhatti is a coder'
print(message.upper())
And we can see that we got our string in uppercase. Similarly, we have a method “lower” to convert the string into lowercase. You can also use the method “title” to capitalize each word of the string.
Note that the method does not change or modify our original string. In fact, it creates a new string and returns it.
3. Find the Sequence of Characters in a String
Let’s try another method to find the index of a particular character in the string.
Type:
message.find('b')
after the same variable and print it. It will print the index of the first occurrence of the letter ‘b’ in the string which is 4 in this case.
Note that this method is case sensitive and it will return -1 if the character is not found in the string. It can also be used for a sequence of characters.
For example, the following program:
message = 'Shahbaz Bhatti is a coder'
print(message.find('coder'))
will return the value “20” as the sequence “coder” starts from index 20.
4. Replacing a Character in a String
You can use the “replace” method to replace a character or a sequence of characters in a string. Let’s see this in action.
message = 'Shahbaz Bhatti is a coder'
print(message.replace('coder', 'programmer'))
This program will replace the word “coder” with “programmer” and print it on the terminal.
5. Check the Existence of a Character in a String
Now there are instances when you want to check the existence of a character or a sequence of the character in your string. In those situations, you can use format your expression like this:
message = 'Shahbaz Bhatti is a coder'
print(‘python’ in message)
Now this will return a boolean function. i.e. “True” or “False”. Like this;
Please note that all these methods and functions are case-sensitive.
Wrap Up!
There is much more to strings, that we will learn gradually as we move forward. Next, we will learn to perform arithmetic operations in Python.
Leave a Reply