Calvin (Deutschbein)
Slides by Jed Rembold
28 February 2022
Suppose you have the string x = "consternation" and you’d like to just extract and print the word "nation". Which expression below will not give you the string "nation"?
x[7:len(x)]x[7:]x[-6:len(x)]x[-6:-1]fleet ⟶ eetflay
orange ⟶ orangeway
def string_2_pig_latin(string):
start = 0
i = 0
phrase = ""
finding_words = True
while len(string) > 0 and finding_words:
if not string[i].isalpha():
word = string[start:i]
phrase += word_2_pig_latin(word) + string[i]
start = i + 1
i += 1
if i == len(string):
finding_words = False
phrase += word_2_pig_latin(string[start:])
return phrase
english.py Libraryenglish module
english module exports two resources:
ENGLISH_WORDS: a constant which contains all the valid English words in alphabetical orderis_english_word(): a predicate function which takes a string as input and returns True or False depending on if that string is in the list of valid English wordsfrom english import ENGLISH_WORDS
def find_first_vowel(word):
for i in range(len(word)):
if word[i].lower() in "aeiou":
return i
return -1
def find_longest_no_vowels():
best_length = 0
for word in ENGLISH_WORDS:
vowel_loc = find_first_vowel(word)
if vowel_loc == -1 and len(word) > best_length:
best_length = len(word)
print(word)
if __name__ == '__main__':
find_longest_no_vowels()
def platin_equals_english():
count = 0
for word in ENGLISH_WORDS:
platin = word_2_pig_latin(word)
if is_english_word(platin) and word != platin:
print(word, ":", platin)
count += 1
return count
A = 10
B = print("The value of A is: " + str(A) +"!")
print(B)
.format() method in Python’s string classformat method and f-strings rely on the idea of a placeholder that is inserted into the string, and that marks where later data should be inserted
{} to indicate the placeholderformat method is acting on, not as an argument to formatformat are then converted to a string if needed and swapped in instead of the placeholder."The value of A is {}".format(10)"{} + {} is {}".format(2, 5, 2+5).format() are positional
{}{ })
"{1} + {0} is {2}".format(2, 5, 2+5)"{name} is {age} years old.".format(age=34, name="Amy")"{} + {B} + {C} = {}".format(3, 10, C=5, B=2)"The value of A is {0:.5f}".format(10)type
precision
Grouping
width
sign
[fill]align
<, >, or ^ for left, right, or center justified| Code | Description |
|---|---|
b |
Inserts an integer using its binary representation |
d |
Inserts an integer using its decimal representation |
e or E |
Inserts a number using scientific notation |
f or F |
Inserts a number using a decimal point format |
g or G |
Choose e or f to get the best fit |
o |
Inserts an integer using its octal representation |
s |
Inserts a string value |
x or X |
Inserts an integer using its hexadecimal representation |
.format() but with less syntaxf right before the string to let Python know it needs to do more with this particular stringA = 10
B = 15.123234
print(f"A is {A} and B is {B:0.2f}")