CommonLounge Archive

Python3 Basics: Strings and Functions

January 23, 2019

In this tutorial, you will learn about strings. We will also learn about functions, objects, methods and type conversions. We have a lot to cover, so let’s dive in.

Strings

In the last tutorial, we learnt that when you say print(something), Python will print the contents and give it to you as output.

What if we wanted to print the letter c ? Let’s see how that’s done:

print('c')

Notice that we did something different this time. We surrounded the letter c with single quotes 'c'. When you want to print letters, you have to put them within the quotes ('), but for printing numbers, we do not put them in quotes.

Notice that you can also use double quotes (") instead of single quotes (') to print a letter. So, you can also do:

print("c")

This will also just print the letter c.

In fact, if you want, you can print not just one letter, but any text the same way. How about Hello, CommonLounge! ?

print('Hello, CommonLounge!')

This program prints Hello Commonlounge!. Awesome!

In the above program, Hello, CommonLounge! is a string.

A string is a sequence of characters that can be processed by a computer. As with individual letters, a string must always be surrounded with quotes — i.e., it should begin and end with the same single (') or double quote ("). The quotes tell Python that what’s inside of them is a string. You can think of a single character as a string of characters, just that the length of the string is 1.

Exercise: Here’s a quick exercise for you. Click Try it now and change the ... part of the code so that it prints your name. Next, hit the Run button to make sure it actually works:

print(...)

Adding two strings

Remember how we added two numbers in the last tutorial?

print(2 + 3)

As it turns out, we can also “add” two strings to each other. In the case of strings, addition joins two strings together. Try this:

print("Hi there " + "CommonLounge")

Output:

Hi there CommonLounge

Notice how we had to end the first string ("Hi there ") with a space (" "). If we did not, then our result would be 'Hi thereCommonlounge', which isn’t what we want. This is something you’ll notice again and again as you learn to code — computer programs are very literal! You have to tell them exactly what you want them to do. If you’re off by even a character, the computer might produce a result you were not expecting. So, you have to be careful and meticulous of small things like these.

Strings in Expressions

We earlier learnt about expressions. We saw that expressions always evaluate to a single value. While we only used numbers inside the expressions, we can also use strings. Let’s look at a few examples.

You can multiply strings with a number:

print("CommonLounge" * 3)

Output:

CommonLoungeCommonLoungeCommonLounge

In Python, multiplying a string by a number (say 3) repeats the string 3 times. This seems like a very helpful feature.

You can combine string and numbers into more complicated expressions as well. Let’s look at a few examples:

print("Hi there " + ("CommonLounge" * 3) + "!")
print("Hi there CommonLounge" + "!" * 10)

Output:

Hi there CommonLoungeCommonLoungeCommonLounge!
Hi there CommonLounge!!!!!!!!!!

Exercise: Suppose you want to create a separator line that looks like 80 - characters next to each other:

--------------------------------------------------------------------------------

Write the print statement to generate this using a single - character.

print(...)

Now, we’ll check your understanding so far with a few questions.

Apostrophe inside a string: “Escaping” characters

If you need to put an apostrophe inside your string, you have two ways to do it.

Using double quotes:

print("Runnin' down the hill")

Output:

Runnin' down the hill

or escaping the apostrophe with a backslash (\).

print('Runnin\' down the hill')

Output:

Runnin' down the hill

Backslash is a special character inside strings — it tells Python that the next character is not meant to be interpreted in the usual way. This is called escaping a character. Thus, by escaping the ' with a \ , we told Python that the apostrophe in the middle of the string is a part of the string, and that it should not end the current string. Since we started the string with a single quote — so Python was expecting another single quote to end the string.

Exercise: Suppose you want to print the statement:

O'Neill exclaimed, "I love learning Python!"

Write the print statement to help you do that:

print(...)

Python Functions

We’ve already seen a very important Python function in action all along the way — the print() function. A function accepts parameters within the parentheses, and does some operations on them. In the case of print(), it just prints the parameter we give it within the parentheses.

Let’s look at another function.

If you want to know the number of letters contained in your name, there is a function for that too!

print(len("CommonLounge"))

Output:

12

Awesome! We have seen two Python functions in action. In the above line of code, we can see both print and len functions in actions. Note that expressions are evaluated from the inside out. That is, Python first calculates len("CommonLounge"), which is 12, and then executes the print() function with that value.

Exercise: What’s the number of characters in the longest English word?

pneumonoultramicroscopicsilicovolcanoconiosis

Use the len() function to find out:

print(...)

Python Objects and Methods

Now let’s learn about another cool concept in Python: objects. What does it mean to be an object? It just means that it comes with its own functions. Functions which come with objects are technically called methods, and are called using a dot . after the object. Let’s clarify this with an example.

The strings that we’ve been dealing with so far are all objects — they come with their own methods. One such method is upper()

To see your name in uppercase letters, simply type:

print("CommonLounge".upper())

Output:

COMMONLOUNGE

You just used the upper method on your string object!

As a quick recap, note the syntactical difference between a function and a method: you call methods with a . at the end of an object (like "CommonLounge".upper()), but you call a function with the parameter placed in parentheses (like len("CommonLounge")).

There’s more to strings and functions in Python, and we’ll be learning about it later in the course in the following tutorials - Python3 Strings and Python3 Functions.

Converting between types

Suppose we want to print the number of digits in a number like 304023? How can we go about doing this?

Let’s see what happens if we try to use the len() function a number.

print(len(304023))

If you try running this code, we get an error! This happens because the len() function expects a string parameter, but we gave it a number.

One way to get rid of this error is to first convert the number to a string before passing it to the len function This is a good point to introduce a new function that helps us do this: the str() function. We will use the str() function to convert anything to a string. Let’s try this:

print(str(304023))

Output:

304023

Great! Our string is ready to be passed to the len() function:

print(len(str(304023)))

Output:

6

It worked! We used the str function inside of the len function. In particular, the step-by-step evaluation of the above is:

len(str(304023))
=> len("304023")
=> 6

We can use the str() function to convert anything to a string. In fact, we have a similar function called int() that helps us convert strings to a number. Here’s a quick example to show you the int function in action.

a = int("100")
print(a + 5)

Output:

105
  • The str function converts things into strings
  • The int function converts things into integers

Important: we can convert numbers into text, but we can’t necessarily convert text into numbers – what would int('hello') be anyway?

You might be wondering how do you know whether there’s a function to convert one thing to another. Don’t worry! We’ll introduce most of the important functions that you’ll need over the course. But, in general, you should Google whenever you’re stuck! Experienced programmers have to Google things all the time too. No one knows all the functions / methods. 🙂

Exercise: What’s the length of 179424691? Write code below to find out:

print(...)

Summary

So far you’ve learned about:

  • strings — used for text objects
  • string expressions — combine strings with + and repeat them over with a *
  • escaping characters — add an apostrophe in the middle of a string by escaping it with a backslash \
  • functions — like len(), perform actions on objects.
  • objects — have methods that can be called with a dot. For example, the string "CommonLounge" is an object, and upper() is a method on it. We call it like this: "CommonLounge".upper()
  • type conversions — You can convert a number to a string using str() function, and a string to a number using the int() function.

These are the basics of every programming language you learn. Ready for something harder? We bet you are!

Based on content from https://tutorial.djangogirls.org/en/python_introduction/


© 2016-2022. All rights reserved.