Vous êtes sur la page 1sur 6

Strings & Variables SSUET/QR/114

LAB # 02
To study the basics about Strings and Variables in Python.

2.1 Strings:
A string is simply a series of characters. Anything inside quotes is considered a string in Python,
and you can use single or double quotes around your strings like this:
"This is a string."
'This is also a string.'
2.1.1 Changing Case in a String with Methods
One of the simplest tasks you can do with strings is change the case of the words in a string.
Look at the following code, and try to determine whats happening:

name = "string python"


Save this file as name.py, and then run it. You should see this output:

Sting Python

In this example, the lowercase string "string python" is stored in the variable name. The method
title() appears after the variable in the print() statement. A method is an action that Python can
perform on a piece of data. The dot (.) after name in name.title() tells Python to make the title()
method act on the variable name. Every method is followed by a set of parentheses, because
methods often need additional information to do their work. That information is provided inside
the parentheses. The title() function doesnt need any additional information, so its parentheses
are empty. Title() displays each word in titlecase, where each word begins with a capital letter.
This is useful because youll often want to think of a name as a piece of information. For
example, you might want your program to recognize the input values String, STRING, and string
as the same name, and display all of them as String. Several other useful methods are available
for dealing with case as well. For example, you can change a string to all uppercase or all
lowercase letters like this:

Strings & Variables SSUET/QR/114


The method upper() returns a copy of the string in which all case-based characters have been
uppercased. The method lower() returns a copy of the string in which all case-based characters
have been lowercased.

The lower() method is particularly useful for storing data. Many times you wont want to trust
the capitalization that your users provide, so youll convert strings to lowercase before storing
them. Then when you want to display the information, youll use the case that makes the most
sense for each string.

2.1.2 Combining or Concatenating Strings:

When applied to strings, the + operation is called concatenation. It produces a new string that is a
copy of the two original strings pasted together end-to-end. Notice that concatenation doesnt do
anything clever like insert a space between the words. The Python interpreter has no way of
knowing that you want a space; it does exactly what it is told.

Strings can be concatenated with the + operator and repeated with *


2.1.3 Indexing of string:

Like the list data type that has items that correspond to an index number, each of a strings
characters also correspond to an index number, starting with the index number 0.

Strings & Variables SSUET/QR/114

For the string Sammy Shark! the index breakdown looks like this:

S a m m Y S h a r k !

0 1 2 3 4 5 6 7 8 9 10 11

As you can see, the first S starts at index 0, and the string ends at index 11 with the ! symbol.

We also notice that the whitespace character between Sammy and Shark also corresponds with
its own index number. In this case, the index number associated with the whitespace is 5.
The exclamation point (!) also has an index number associated with it. Any other symbol or
punctuation mark, such as *#$&.;?, is also a character and would be associated with its own
index number.
2.1.4 Accessing Characters by Negative Index Number:
If we have a long string and we want to pinpoint an item towards the end, we can also count
backwards from the end of the string, starting at the index number -1.
For the same string Sammy Shark! the negative index breakdown looks like this:

S a m m Y S h a r k !

-12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

By using negative index numbers, we can print out the character r, by referring to its position at
the -3 index, like so:




Using negative index numbers can be advantageous for isolating a single character towards the
end of a long string.
2.1.5 Slicing Strings:
We can also call out a range of characters from the string. Say we would like to just print the
word Shark. We can do so by creating a slice, which is a sequence of characters within an
original string. With slices, we can call multiple character values by creating a range of index
numbers separated by a colon [x:y]:


Strings & Variables SSUET/QR/114

When constructing a slice, as in [6:11], the first index number is where the slice starts
(inclusive), and the second index number is where the slice ends (exclusive), which is why in our
example above the range has to be the index number that would occur just after the string ends.

If we want to include either end of a string, we can omit one of the numbers in
the string[n:n] syntax. For example, if we want to print the first word of string ss Sammy
we can do so by typing:



2.2 Counting Methods

While we are thinking about the relevant index numbers that correspond to characters within
strings, it is worth going through some of the methods that count strings or return index numbers.
This can be useful for limiting the number of characters we would like to accept within a user-
input form, or comparing strings. Like other sequential data types, strings can be counted
through several methods.

Well first look at the len() method which can get the length of any data type that is a sequence,
whether ordered or unordered, including strings, lists, tuples, and dictionaries.
The len() method counts the total number of characters within a string.

print(len("Let's print the length of this string."))


If we want to count the number of times either one particular character or a sequence of
characters shows up in a string, we can do so with the count()
We can also find at what position a character or character sequence occurs in a string. We
can do this with the find() method, and it will return the position of the character based
on index number.

Strings & Variables SSUET/QR/114

2.3 Variables:

Variables are nothing but reserved memory locations to store values. This means that
when you create a variable you reserve some space in memory.

Based on the data type of a variable, the interpreter allocates memory and decides what
can be stored in the reserved memory. Therefore, by assigning different data types to
variables, you can store integers, decimals or characters in these variables.

Python variables do not need explicit declaration to reserve memory space. The
declaration happens automatically when you assign a value to a variable. The equal sign
(=) is used to assign values to variables.

Variable names can contain only letters, numbers, and underscores. They can start with a
letter or an underscore, but not with a number. Spaces are not allowed in variable names,
but underscores can be used to separate words in variable names.

message = "Hello Python world!"

Hello Python world!

Weve added a variable named message. Every variable holds a value, which is the
information associated with that variable. In this case the value is the text Hello Python

Lab Exercise:
1. Write a Python script that prints BIO-DATA.

2. Write a Python script that store a persons name in a variable, and then print that persons
name in uppercase, and titlecase.

3. Write a Python script that store a string in a variable and ask some word in the given
string using find() and in the return their index value as a output.

4. Write a Python program to lowercase first nth characters in a string.

5. Write a Python script that asks users for their favourite color. Create the following output
(assuming blue is the chosen color) (hint: use + and *)
blue blue

Strings & Variables SSUET/QR/114