Strings

Data Types in Python

Jason Myers

Instructor

Creating formatted strings

  • f-strings (formatted string literals) - f""
cookie_name = "Anzac"
cookie_price = "$1.99"

print(f"Each { cookie_name } cookie costs { cookie_price }.")
"Each Anzac cookie costs $1.99."
Data Types in Python

Joining with strings

  • "".join() uses the string it's called on to join an iterable
child_ages = ["3", "4", "7", "8"]

print(", ".join(child_ages))
"3, 4, 7, 8"
print(f"The children are ages {','.join(child_ages[0:3])}, and {child_ages[-1]}.")
"The children are ages 3, 4, 7, and 8."
Data Types in Python

Matching parts of a string

  • .startswith() and .endswith() methods will tell you if a string starts or ends with another character or string
boy_names = ["Mohamed", "Youssef", "Ahmed"]
print([name for name in boy_names if name.startswith('A')])
["Ahmed"]
  • Be careful as these and most string functions are case-sensitive.
Data Types in Python

Searching for things in strings

  • The in operator searches for some value in some iterable type like a string.
"long" in "Life is a long lesson in humility."
True
"life" in "Life is a long lesson in humility."
False
Data Types in Python

An approach to being case insensitive

  • .lower() method returns a lower case string
"life" in "Life is a long lesson in humility.".lower()
True
Data Types in Python

Let's practice!

Data Types in Python

Preparing Video For Download...