Fall 2024 - P4
Big Idea 3 | .1 | .2 | .3 | .4 | .5 | .6 | .7 | .8 | .10 |
Lesson 4.1 Strings
Strings in Python:
Printing
- you can print the string directly or use variables to store it
#printing directly, use single or double qutoes:
print("panda")
#variable = "string"
animal = "rabbit"
#keep variable descriptive of what value it holds to make code easier to read
#single or double quotes both work
#variables with multiple words, use underscore not space
favorite_animal = "otter"
#don't use quotes when using variables
print(animal)
print(favorite_animal)
panda
rabbit
otter
Quotes:
- if using single quotes and string has a single quote, python will read it as the end of a string
- to combat this, use a backslash or double quotes
- vice versa for double quotes
# example: mood1 = 'I'm feeling tired'
#apostrophe in "I'm" interrupts string and will cause error
#use backslash in front or double quotes
mood2 = 'I\'m feeling happy'
mood3 = "I'm feeling sad"
print(mood2)
print(mood3)
I'm feeling happy
I'm feeling sad
Strings with multiple lines
- instead of printing 3 separate strings, use 3 quotes
- both single and double work
riddle = """my favorite animal
hiberates during the winter
in a cave"""
print(riddle)
my favorite animal
hiberates during the winter
in a cave
len function
- stands for length
- returns length of a string
print(len ("hummingbird"))
11
Printing specific parts of a string
- for a specific character: use []
- for a range: use [ : ]
- starts counting at 0
- first value is inclusive, second is not
- slicing:
- leaving first value empty: will start at 0
- leaving second value empty: will end with last character
tiger_fact = "the stripes on a tiger are unique, similar to human fingerprints"
#specific character:
print(tiger_fact[5])
#range:
print(tiger_fact[4:11])
#slicing:
print(tiger_fact[:23])
print(tiger_fact[35:])
t
stripes
the stripes on a tiger
similar to human fingerprints
Palindromes
A palindrome is a string that reads the same from right to left as left to right.
def palindrome(input_str):
# Remove spaces and convert the string to lowercase
clean_str = input_str.replace(" ", "").lower()
# Check if the cleaned string is equal to its reverse
return clean_str == clean_str[::-1]
print(palindrome("go hang a salami im a lasagna hog")) # True
print(palindrome("hi")) # False
True
False