Warning - This site is moving to https://getthecodingbug.anvil.app
Topics covered
String Formatting
Basic String Operations
Conditions
Boolean operators
The "in" operator
Indentation, if, else and elif
The 'is' operator
String Formatting
Python uses C-style string formatting to create new, formatted strings.
The "%" operator is used to format a set of variables enclosed in a "tuple" (a fixed size list), together with a format string, which contains normal text together with argument specifiers, special symbols like "%s" and "%d".
Let's say you have a variable called "name" with your user name in it, and you would then like to print out a greeting to that user.
# Printing, using argument specifiers
name = "John"
print("Hello, %s!" % name)
results in:
Hello, John!
To use two or more argument specifiers, use a tuple (parentheses):
# Printing, using argument specifiers with parentheses
name = "John"
age = 23
print("%s is %d years old." % (name, age))
results in:
John is 23 years old.
Any object which is not a string can be formatted using the %s operator as well.
The string which returns from the "repr" method of that object is formatted as a string, for example:
# Printing non-string objects
mylist = [1,2,3]
print("A list: %s" % mylist)
results in:
A list: [1, 2, 3]
Here are some basic argument specifiers you should know:
%s - String (or any object with a string representation, like numbers)
%d - Integers
%f - Floating point numbers
%.<number of digits>f - Floating point numbers with a fixed amount of digits to the right of the dot.
%x/%X - Integers in hex representation (lowercase/uppercase)
Exercise
You will need to write a format string which prints out the data using the following syntax:
"Hello John Doe. Your current balance is $53.44."
# Exercise - result should be "Hello John Doe. Your current balance is $53.44."
data = ("John", "Doe", 53.44)
format_string = "Hello"
print(format_string % data)
Hint: add some argument specifiers after 'Hello'
Basic String Operations
Strings are bits of text. They can be defined as anything between quotes:
# string delimiters - you can use single or double-quotes
astring = "Hello world!"
astring2 = 'Hello world!'
As you can see, the first thing you learned was printing a simple sentence.
This sentence was stored by Python as a string.
However, instead of immediately printing strings out, we will explore the various things you can do to them.
You can also use single quotes to assign a string. However, you will face problems if the value to be assigned itself contains single quotes.
For example to assign the string in these brackets (single quotes are ' ') you need to use double quotes only like this
# string delimiters - quotes inside strings
print("single quotes are ' '")
print(len(astring))
The following prints out 12, because "Hello world!" is 12 characters long, including punctuation and spaces.
# string length
astring = "Hello world!"
print(len(astring))
You can also find occurrences a character in a string:
# string indexing
astring = "Hello world!"
print(astring.index("o"))
This prints out 4, because the location of the first occurrence of the letter "o" is 4 characters away from the first character.
Notice how there are actually two o's in the phrase - this method only recognizes the first.
But why didn't it print out 5? Isn't "o" the fifth character in the string?
To make things more simple, Python (and most other programming languages) start things at 0 instead of 1.
So the index of "o" is 4.
You can also find occurrences a character in a string:
# character counting astring = "Hello world!"
print(astring.count("l"))
It might look like digit '1', but it is a lowercase L. . We are counting the number of occurrences of it in the string.
Therefore, it should print 3.
You can slice up strings, like this:
# string slicing astring = "Hello world!"
print(astring[3:7])
results in:
lo w
That is, it prints a slice of the string, starting at index 3, and ending at index 6.
But why 6 and not 7? Again, most programming languages do this - it makes doing math inside those brackets easier.
If you just have one number in the brackets, it will give you the single character at that index.
If you leave out the first number but keep the colon, it will give you a slice from the start to the number you left in.
If you leave out the second number, if will give you a slice from the first number to the end.
You can even put negative numbers inside the brackets. They are an easy way of starting at the end of the string instead of the beginning.
This way, -3 means "3rd character from the end".
# more string slicingastring = "Hello world!" print(astring[3:10:2])
results in:
l ol
This prints the characters of string from 3 to 9 skipping every other character. This is extended slice syntax.
The general form is [start:stop:step].
There is no function, like strrev in C, to reverse a string. But with the above mentioned type of slice syntax you can easily reverse a string like this:
# reversing a string, using slicingastring = "Hello world!"
print(astring[::-1])
results in:
!dlrow olleH
These make a new string with all letters converted to uppercase and lowercase, respectively.
# converting to upper or lower caseastring = "Hello world!"
print(astring.upper())
print(astring.lower())
You can determine whether the string starts with something or ends with something, respectively.
The first one will print True, as the string starts with "Hello".
The second one will print False, as the string certainly does not end with "asdfasdfasdf".
# testing for what a string starts or ends with
astring = "Hello world!"
print(astring.startswith("Hello"))
print(astring.endswith("asdfasdfasdf"))
You can split a string into a list, by specifying a separator character
# splitting a string
astring = "red lorry yellow lorry"alist = astring.split(" ")
print(alist)
results in:
['red', 'lorry', 'yellow', 'lorry']
But specifying a different separator character
# splitting a string
astring = "red lorry yellow lorry"alist = astring.split("l")
print(alist)
results in:
['red ', 'orry ye', '', 'ow ', 'orry']
Exercise
Try to fix the code to print out the correct information by changing the string.
s = "Hey there! what should this string be?"
# Exercise s = "Hey there! what should this string be?"
# Length should be 20
print("Length of s = %d" % len(s))
# First occurrence of "a" should be at index 8
print("The first occurrence of the letter a = %d" % s.index("a"))
# Number of a's should be 2
print("a occurs %d times" % s.count("a"))
# Slicing the string into bits
print("The first five characters are '%s'" % s[:5]) # Start to 5
print("The next five characters are '%s'" % s[5:10]) # 5 to 10
print("The thirteenth character is '%s'" % s[12]) # Just number 12
print("The characters with odd index are '%s'" %s[1::2]) #(0-based indexing)
print("The last five characters are '%s'" % s[-5:]) # 5th-from-last to end
# Convert everything to uppercase
print("String in uppercase: %s" % s.upper())
# Convert everything to lowercase
print("String in lowercase: %s" % s.lower())
# Check how a string starts
if s.startswith("Str"):
print("String starts with 'Str'. Good!")
# Check how a string ends
if s.endswith("ome!"):
print("String ends with 'ome!'. Good!")
# Split the string into three separate strings, each containing only a word
print("Split the words of the string: %s" % s.split(" "))
Conditions
Python uses boolean variables to evaluate conditions. The boolean values True and False are returned when an expression is compared or evaluated, for example:
# conditions x = 2
print(x == 2) # prints out True
print(x == 3) # prints out False
print(x < 3) # prints out True
Notice that variable assignment is done using a single equals operator "=", whereas comparison between two variables is done using the double equals operator "==". The "not equals" operator is marked as "!=".
Boolean operators
The "and" and "or" boolean operators allow building complex boolean expressions, for example:
# Boolean operators name = "John"
age = 23
if name == "John" and age == 23:
print("Your name is John, and you are also 23 years old.")
If name == "John" or name == "Rick":
print("Your name is either John or Rick.")
The "in" operator
The "in" operator can be used to check if a specified object exists within an iterable object container, such as a list:
# using the 'in' operator name = "John"
if name in ["John", "Rick"]:
print("Your name is either John or Rick.")
Indentation, if, else and elif
Python uses indentation to define code blocks, instead of brackets.
The standard Python indentation is 4 spaces, although tabs and any other space size will work, as long as it is consistent.
Notice that code blocks do not need any termination.
Here is an example for using Python's "if" statement using code blocks:
# code blocks if <statement is true>:
<do something>
....
....
elif <another statement is true>: # else if
<do something else>
....
....
else:
<do another thing>
....
....
Another example:
# code blocks x = 2
if x == 2:
print("x equals two!")
else:
print("x does not equal to two.")
A statement is evaluated as true if one of the following is correct:
1. The "True" boolean variable is given, or calculated using an expression, such as an arithmetic comparison.
2. An object which is not considered "empty" is passed.
Here are some examples for objects which are considered as empty:
1. An empty string: ""
2. An empty list: []
3. The number zero: 0
4. The false boolean variable: False
The 'is' operator
Unlike the double equals operator "==", the "is" operator does not match the values of the variables, but the instances themselves, for example:
# the 'is' operator x = [1,2,3]
y = [1,2,3]
print(x == y) # Prints out True
print(x is y) # Prints out False
The "not" operator
Using "not" before a boolean expression inverts it, for example:
# the 'not' operator print(not False) # Prints out True
print((not False) == (False)) # Prints out False
Exercise
Change the variables in the first section, so that each if statement resolves as True.
# change the next 4 lines
number = 10
second_number = 10
first_list = []
second_list = [1,2,3] # then check your changes here
if number > 15:
print("1")
if first_list:
print("2")
if len(second_list) == 2:
print("3")
if len(first_list) + len(second_list) == 5:
print("4")
if first_list and first_list[0] == 1:
print("5")
if not second_number:
print("6")
You should get the following if you made the correct changes:
1
2
3
4
5
6
>>>