loops + strings (slides)

CSc 110 - looping through strings

String Manipulation

String indexing

  • Strings are sequences in Python
  • We can retrieve values in a sequence using [ ]
name = "Xinchen"
name[0]
'X'

Note that the first index in a sequence is always zero.

String indexing

Since the first index of a sequence is zero, the last index is going to be the length of the string minus 1

name = "Xinchen"
len(name)
7
name = "Xinchen"
name[6]
'n'
name = "Xinchen"
name[7] # this will throw an error

in operator

The in operator determines whether a given value is a constituent element of a sequence (such as a string)

"i" in "aeiou"
True
"eio" in "aeiou"
True
not "b" in "aeiou"
True
"0" in  "0987654321."
True
"10.0" in  "0987654321."
False

String + while + if

Print only digits, one at a time.

string = "BladeRunner2049"
i = 0
while i < len(string):
  if string[i] in "0123456789":
    print(string[i])
  i += 1
2
0
4
9

Write a function

Write a function count_nondigits to return the number of characters that are not digits (0-9) in a string.

assert count_nondigits("BladeRunner2049") == 11
assert count_nondigits("2049") == 0
assert count_nondigits("abc0123") == 3

Write a function - solution

def count_nondigits(string):
  index = 0
  count = 0
  while index < len(string):
    if string[index] not in "0123456789":
      count += 1
    index += 1
  return count

def main():
  assert count_nondigits("BladeRunner2049") == 11
  assert count_nondigits("2049") == 0
  assert count_nondigits("abc0123") == 3
  
main()

Question

How to check if a string can be converted to an integer or float?

Can we use the string method.isnumeric()?

user_input = "BladeRunner2049"
user_input.isnumeric()
False
user_input = "2049"
user_input.isnumeric()
True
user_input = "12.5"
user_input.isnumeric()
False

Write a function

Function name is_numeric that takes one string argument of any length (assume length > 0).

It returns True if every character in the argument is a digit (0-9) or a period (.), False otherwise.

Use in operator instead of built-in function isnumeric().

assert is_numeric("BladeRunner2049") == False
assert is_numeric("2049") == True
assert is_numeric("12.5") == True
assert is_numeric("1.2.5") == False

is_numeric() – solution

def is_numeric(my_string):
  index = 0
  count_period = 0
  while index < len(my_string):
    if my_string[index] == ".":
      count_period += 1
    if my_string[index] not in "0123456789." or count_period > 1:
      return False
    index += 1
  return True

def main():
  assert is_numeric("234") == True
  assert is_numeric("abc") == False
  assert is_numeric("12c") ==  False
  assert is_numeric("12.3") == True
  assert is_numeric("1.2.3") == False
  
main()