4.2 — String methods, break & continue statements

in operator (membership operator)

  • In Python in is a keyword.
  • The in and not in operators test for membership.
  • We can use them with strings to test if one string is a substring of another. This operation is case-sensitive.
1s = "Pineapple"
2
3print("app" in s) # True
4print("pine" in s) # False
5
6print("x" not in s) # True
7print("P" not in s) # False

Try the problem “Remove Duplicates” on Ed Lessons.

Try the problem “Benchpress” on Ed Lessons.

String methods

A method is similar to a function except that a method is always called on an object:

object.method_name(argument1, argument2, …)

str type has several methods that we can call on a string object:

1print("hello".upper()) # calling method upper() on the string "hello"
2# HELLO
3
4message = "hello"
5print(message.upper()) # using variable that refers to string
6# HELLO
7
8message = 10
9print(message.upper()) # upper() only available for str objects
10# AttributeError: 'int' object has no attribute 'upper'

Useful string methods

1s = "Luke, I am your father"
2
3# s.lower() : returns a copy of s, but with all lower case letters.
4print(s.lower())
5# luke, i am your father
6
7# s.upper() : returns a copy of s, but with all upper case letters.
8print(s.upper())
9# LUKE, I AM YOUR FATHER

1s = "Luke, I am your father"
2# s.replace(old, new) : returns a copy of s with all occurrences of
3# the substring old replaced by new.
4print(s.replace("am", "am not"))
5# Luke, I am not your father
6
7# replace space with empty string
8print(s.replace(" ", ""))
9# Luke,Iamyourfather

1s = "banana"
2# s.count(c) : returns the number of non-overlapping
3# occurrences of substring c in s.
4print(s.count("na"))
5# 2
6
7# s.find(c) : returns the index where the substring begins in s begins.
8# If c is not a substring of s, then -1 is returned.
9print(s.find("an"))
10# 1
11
12print(s.find("naa"))
13# -1

1x = 1
2y = 2.5
3z = 3.14
4name = "Reza"
5
6# fmt.format(a1, a2, ...):
7# returns a string where the placeholders {} in format string fmt
8# are replaced by args a1, a2, etc.
9
10print("x = {}, y = {}".format(x, y))
11# x = 1, y = 2.5
12
13print("Point: ({}, {}, {})".format(x, y, z))
14# Point: (1, 2.5, 3.14)
15
16print("Welcome {}!".format(name))
17# Welcome Reza!

Formatted Strings

1x = 1
2y = 2.5
3z = 3.14
4name = "Reza"
5
6print(f"x = {x}, y = {y}")
7# x = 1, y = 2.5
8
9print(f"Point: ({x}, {y}, {z})")
10# Point: (1, 2.5, 3.14)
11
12print(f"Welcome {name}!")
13# Welcome Reza!

Example

In just one expression, compare if two strings s1 and s2 are equal in a case-insensitive manner.

1s1 = "Hello Everyone"
2s2 = "hello everyone"
3
4is_equal = s1.upper() == s2.upper()
5
6# OR
7# is_equal = s1.lower() == s2.lower()
8
9print(is_equal) # prints True

break statement

break statement can be used to terminate a loop before it normally ends.
After a break statement is executed, no other code inside the loop is executed.

1for i in range(10):
2 if i > 5:
3 break
4 print(i)
5
6print("Bye!")
Output
0
1
2
3
4
5
Bye!

Write a function is_prime that takes an integer as argument and returns True if the number is prime, otherwise returns False. To check if a number n is prime:

  • Assume n is prime
  • Divide n by each number i from 2 to n-1
    • if n is divisible by any i then n cannot be not prime

In other words, if n is not divisible by all i’s then n is prime.

1def is_prime(num):
2 prime = True
3
4 if num < 2:
5 prime = False
6 else:
7 for i in range(2, num):
8 if num % i == 0:
9 prime = False
10 break
11
12 return prime
13
14print(is_prime(7)) # True
15print(is_prime(21)) # False

1password = input("Enter password: ")
2
3while password != "abcd1234":
4 print("Incorrect password, try again!")
5 password = input("Enter password: ")
6
7print("Login successful!")

Change above program so that it keeps asking email and password until both are correct.
Password comparison must be case-sensitive, while email comparison should be case-insensitive.
For comparison, just choose any email, password that you like.

1email = input("Enter email: ")
2password = input("Enter password: ")
3
4while email.lower() != "abcd@gmail.com" or password != "1234":
5 print("Incorrect email or password, try again!")
6
7 email = input("Enter email: ")
8 password = input("Enter password: ")
9
10# If we reach this line it means both email and password were correct
11print("Login successful!")

Using break in a while loop

We can simplify the login example using a break statement:

1while True:
2 email = input("Enter email: ")
3 password = input("Enter password: ")
4 if email.lower() == "abcd@gmail.com" and password == "1234":
5 break
6 print("Incorrect email or password, try again!")
7
8print("Login successful!")

continue statement

continue statement is useful to skip some steps in a loop.

After a continue statement is executed, code that follows the statement is skipped and execution continues from the next step of the loop.

1for i in range(1, 50):
2 if i % 2 == 0 or i % 3 == 0:
3 continue
4 print(i)
Output
1 5 7 11 13 17 19 23 25 29 31 35 37 41 43 47 49