You are on page 1of 24

IT Automation

INFO8025
Conestoga College
IT AUTOMATION – INFO 8025
Topic 14 – Strings; Loops
Objectives
• String Manipulation
• Loops in Python
- while loop
- for loop
- range() function
• Hands-on Time
Strings are Arrays
• Strings are arrays, sequence of characters.
• To access elements of a string we use the zero-based index in square brackets

a = "Hello, World!"
print(a[1]) #accessing and printing out the element found at the 2 nd
position

Output: e

• To get the length of a string:


- len() function

- Example:
myText = "Hello, World!“
strLength = len(myText) # 13 would be saved to strLength variable
String Methods
There is a number of built-in methods that can be called with strings.

• strip() - removes any whitespace from the beginning and the end of a string.

a = " Hello, World! “


a = a.strip()
print(a)  #Output: Hello, World!
• lstrip() - removes any whitespace from the left side (beginning) of a string
• rstrip() - removes any whitespace from the right side (end) of a string

• lower() - returns a string in lower case.


a = " Hello, World! "
print( a.lower() )  #Output: hello, world!

• upper() - returns a string in upper case.


a = "Hello, World!"
print(a.upper()) #Output: HELLO, WORLD!
String Methods, cont’d
• replace() - replaces all occurrences of a substring found in a string, with another string
a = "Hello, World!"
print(a.replace(“W”, “J”)) #Output: Hello, Jorld!

• split() - splits the string into substrings (ie. multiple strings) if it finds instances of the separator:
a = "Hello, World!"
print(a.split(","))  # Output is a List object: ['Hello', ' World!’]

• All methods that return a string, return a new string object - ie. they do not change the original string.
a = "Hello, World!“
b = a.replace(“W”, “J”)
print(a) #The original string remained the same. Output: Hello, World!
print(b) #The new value; Output: Hello, Jorld!

- To retain the effects of a method we need to save its return value to a variable.
- Can use the original variable or create a new one. Will depend on whether we need to refer to the initial value
later on in code.
Additional String Methods
text = “python is Easy to Learn.“

• capitalize() Converts the first character of the first word to upper case and the rest of the characters to lower
text.capitalize() # returns “Python is easy to learn.”
• title() Converts the first character of each word to upper case
text.title() # returns “Python Is Easy To Learn.”
• startswith() Returns True if the string starts with the specified value
text.startswith(‘python is Easy’) # returns True
• endswith() Returns True if the string ends with the specified value
text.endswith(‘to Learn.’) # returns True
• count() Returns the number of times a specified value occurs in a string
text.count(‘y’) # returns 2
• find() Searches the string for a specified value and returns the position of where it was first found;
returns -1 if the value is not found in the string
text.find(‘y’) # returns 1
• rfind() Searches the string for a specified value and returns the last position of where it was found
text.rfind(‘y’) # returns 13
Additional String Methods, cont’d
text1 = “Python is easy 2 learn.“
• isspace() Returns True if all characters in the string are whitespaces
• isalpha() Returns True if all characters in the string are letters
• isalnum() Returns True if all characters in the string are alphanumeric

text1.isalnum() # returns False, because of the whitespaces and the dot

• isdecimal() Returns True if all characters in the string are decimals - supports only numbers 0-9
• isdigit() Returns True if all characters in the string are digits - supports numbers 0-9, subscripts, superscripts
• isnumeric() Returns True if all characters in the string are numeric - supports numbers 0-9, subscripts,
superscripts, fractions, Roman numerals
• None of the previous three methods will recognize a decimal number as a number. One way to check if a value is a
decimal number, is to find a decimal point (count()), get rid of it (replace() ), and then use one of the three methods
above:
text2 = 123.45
text2.isdecimal() # returns False
text2 = text2.replace(‘.’,’’)
text2.isdecimal() # returns True
Comparing Strings
• The two basic string comparison operators are == and !=
They work with strings the same way as with integer and float values:
- The == operator returns True if there is an exact match, otherwise False will be returned.
- The != operator returns True if there is no match and otherwise returns False.

• Comparing the string with == and != is case sensitive.


a = ‘hello’
b = ‘Hello’
if (a == b): # this will return False
# do something…

• To do a case-insensitive comparison, we can convert both strings to uppercase or to lowercase letters and then
compare them
if ( a.lower() == b.lower() ): # this will return True
# do something….
Checking String Content
• To check if a string is present in another string, we can use the keywords in and not in

• The value returned is True or False.

• Example:
myText = “Python is easy to learn.“

isFound = “eas" in myText #Checks if “eas” is contained in myText


print(isFound) #Output: True

isFound = “eas“ not in myText #Checks if “eas” is not contained in myText


print(isFound) #Output: False
String Concatenation & Escape Character
• To concatenate, or combine, two strings we can use the + operator
a = "Hello"
b = "World"
c = a + " " + b #Combines the two strings and also adds a space in between
print(c) #Output: Hello World

• The escape character \ (backslash) is used before double or single quotes that we want to include in a
string.

text = "Odessa – the so-called "Pearl of the Black Sea"." #this would result in an error.
text = "Odessa – the so-called \"Pearl of the Black Sea\"." #this would work.

print(text) #Output: Odessa – the so-called "Pearl of the Black Sea".


String concatenation, cont’d
• We use + operator to concatenate strings

• We cannot use + to concatenate strings and numbers in the same way:


age = 70
text = "I am " + age + “ years old” #this will result in an error
print(text)

• Option 1: Cast the number to string


age = 70
text = "I am " + str(age) + “ years old” #this will work
print(text)

• Option 2: use the format() method (see the next slide)


String format() method
• format() method takes in parameters we pass to it and places them in the string on which the method is called
wherever the placeholders {} in the string are:
age = 70
text = "I am {} years old." # The string we want to format; it has a {} – a placeholder
print( text.format(age) ) # calling the string format() method with the parameter
• The number of parameters with format() method is unlimited; they are each placed into its respective placeholder.
quantity = 2
itemNo = 123
itemPrice = 19.98

order = "I would like to order {} pieces of item {} at a price of ${} per item.“ # the string being
formatted
print( order.format(quantity, itemNo, itemPrice) )

• To be sure the arguments are placed in the correct placeholders, we have the option to use the zero-based index
referencing the position of the parameter to use with a placeholder:

order = "I would like to order {2} pieces of item {0} at a price of ${1} per item."
print( order.format(itemNo, itemPrice, quantity) )
Loops
• Python supports two types of loops: while and for
While Loop
• We use a while loop when we want to execute a set of statements as long as the specified condition is true.
- Example:

#Printing i as long as it is less than 6


i = 1 # i is initialized to the value of 1
while i < 6: # the condition
print(i) # this runs as long the condition specified evaluates to true
   i += 1 # incrementing i, or else the loop would continue forever
# the code in the loop will print out the values 1 through 5

• break statement – used to stop the loop - even while the condition still evaluates to true
i = 1
while i < 6:

print(i)
if i == 3:
     break # Exit the loop when i is 3; Only the numbers 1, 2 and 3 will be printed out.  

i += 1
While Loop
• continue statement - used to stop the current iteration, and continue with the next
# note that the increment logically needs to come before the continue statement
otherwise once i hits 3 the increment won't happen anymore because of the continue statement; i would continue to be 3
forever.
i = 0
while i < 6:
i += 1
if i == 3:
     continue # if i is 3 do nothing but continue to the next iteration;
   print(i) # will print out 1, 2, 4, 5

• else statement - used to run a block of code once more, after the condition stops evaluating to true
i = 1
while i < 6:
print(i) # will print out numbers 1 through 5
   i += 1
else:
   print("i is no longer less than 6") # Print the message once the condition evaluates to
false
For Loop
• Less like the For loop in PowerShell (and other languages) and more like foreach loop
• Used for iterating over a sequence of values (a list, a tuple, a dictionary, a set, or a string)
- It is used for executing one or more statements, once for each item
- We will start by looking at how it works with strings, as each string is an array (a sequence of characters)

• Example:
myText = “College”
for x in myText: # Looping through the letters in the word “College"
   print(x) # Printing each letter of the word - one letter per iteration

• break statement - used to stop the loop before it has looped through all the items
for x in “College":
if x == “l":
     break # Exit the loop when x is “l“; note that here the break comes before the print
   print(x)    # Printing the letter from the current itteration; only the letters ‘C’ and ‘o’ will be printed
For Loop
• continue statement – stops the current iteration of the loop, and continues with the next

for x in "College":
if x == "o":
     continue # Do not print o
   print(x) # printing the current letter
# all the letters but ‘o’ will be printed

• else statement - specifies a block of code to be executed once the loop is finished.
Note: If the loop is stopped with a break statement, the else does not run.

for x in “College": #Looping through the letters in the word “College"


   print(x) # printing the current letter; all letters will be printed
else:
print(“All done!”)
For Loop
Example: continue, break, else in a loop:

for x in "College": #Looping through the letters in the word “College"


if x == 'l':
continue # skip the current iteration
elif x == 'g':
break # breaks out of the loop; prevents the loop’s else from running

print(x) # printing the current letter; letters 'l', 'g', and 2nd 'e' will not be printed
else: # the loop’s else statement
print("All done!“) # Print the message once the loop went through all the elements.
# Will not run due to the break statement

- The output:
C
o
e
For loop with range() function
• The range() function generates a sequence of numbers
• By default, the sequence starts from 0, increments by 1, and ends at the specified number - 1.
numSequence = range(6) # will generate a sequence of numbers from 0 to 5

• range() function can be used in a for loop when we want to execute some code a specified number of times.

for x in range(6): # range(6) generates numbers 0 - 5


print(x) # printing numbers from 0 to 5, one number per each loop iteration

• We can specify a starting value other than 0, by adding a parameter in the 1st position: 
for x in range(2, 6): # range(2, 6) generates numbers 2 to 5
print(x) # printing numbers from 2 to 5, one number per each loop iteration

• We can specify an increment other than 0, by adding a parameter in the 3rd position: 
for x in range(2, 15, 3): # generated numbers start at 2 and go to the maximum of 14, with an increment of 3
print(x) # printing numbers 2, 5, 8, 11, 14, one number per each loop iterations
Troubleshooting your Code
• There are syntax and logical errors.
• After running your code check the PROBLEMS tab in the Terminal for a list of syntax errors.
• If your code runs without reporting any errors back to you, but still the results are not what you expect
them to be, check your code for possible logical errors.
• If you can’t figure out what is causing the issue in your script, take a step back: start checking the code
section by section.
Do this by commenting out some of the code and leaving only the sections you want to check
first, to see if they work. If they do, start adding back in some of the remaining code, by
uncommenting it. After confirming that that code works as expected, uncomment some
more code and see if it runs without issues. Continue the process until you are able to find
and fix the issue.
Questions?
References
• https://www.w3schools.com/python/python_strings.asp
• https://www.w3schools.com/python/python_while_loops.asp
• https://www.w3schools.com/python/python_for_loops.asp

You might also like