Fall 2024 - P1
Big Idea 3 | .1 | .2 | .3 | .4 | .5 | .6 | .7 | .8 | .10 |
3.4 Strings
Student led teaching on Strings. Learn how strings are sequences of characters used to represent text and how to manipulate them.
Strings
- Strings are ordered sequence of characters (characters = numbers, letters, even space)
- Substring is part of an existing string
- Some procedures exist that can be used with strings, each language has its own functions
- len (str)
- Returns the number of characters in the string
len ("APCSP")
# returns 5, length of the string
5
- Concat
- Merges both strings together, returns it so that they are one word </span>
concat = "AP" + "CSP"
# Concat is simply a variable
print(concat)
Popcorn hack #4:
Find the number of characters in your last name using len. Use concat to merge your first and last name together. Use Substring to show only the 3rd to 6th characters.
#Find the number of characters in your last name using len.
length = len("Bharadwaj")
print(length)
# Use concat to merge your first and last name together.
concat = "Aditi" + "Bharadwaj"
print (concat)
# Use Substring to show only the 3rd to 6th characters.
# be sure to start at 2 because it starts counting at 0
substring = concat[2:6]
print (substring)
9
AditiBharadwaj
itiB
Palindromes
A palindrome is a string that reads the same from right to left as left to right. For example, 2112 and mom are palindromes
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("taco cat")) # True
print(palindrome("hi")) # False
True
False
Hacks
Review each of the sections above and produce …
- CREATE TEXT (string) ANALYZER:
- Accepts input from user
- Counts total letters, numbers, spaces in a string
- Counts number of vowels
- Calculates average word length
- Correctly displays: total # of characters (including spaces + numbers), total vowels, average word length other criteria:
- ensure that program handles upper and lowercase spelling
- Test multiple inputs to ensure accuracy
- Add a unique program, function, or feature not specified by criterion