python102.py
#!/bin/python3
#Importing
print("Importing is important:")
import sys #system functions and parameters
from datetime import datetime
print(datetime.now())
from datetime import datetime as dt #importing with an alias
print(dt.now())
#def new_line():
# print('\n')
#new_line()
#Advanced Strings
print("Advanced Strings")
my_name = "James"
print(my_name[0]) #first initial
print(my_name[-1]) #last letter
#print(my_name[len(my_name)-1]) #last letter
sentence = "This is a sentence."
print(sentence[:4]) #first word
print(sentence[-9:]) #last word
print(sentence[-9:-1]) #last word minus period
print(sentence.split()) #split sentence by delimiter (default space)
sentence_split = sentence.split() #now an array
sentence_join = ' '.join(sentence_split) #join each element with a space between
print(sentence_join) #reconstructed
print('\n'.join(sentence_split)) #join each element with a new line
quoteception = "I said, 'give me all the money'"
print(quoteception)
quoteception = "I said, \"give me all the money\"" #escape quotes
print(quoteception)
print("A" in "Apple") #boolean
letter = "a"
word = "Apple"
print (letter in word)
print(letter.lower() in word.lower()) #improved - case insensitive
word_two = "Bingo"
print((letter.lower() in word.lower()) and not (letter.lower() in word_two.lower()))
space = " hello "
print(space.strip()) #default removes spaces
full_name = "eath Adams"
print(full_name.replace("eath", "Heath"))
index_of_last_name = full_name.find("Adams")
print(full_name[index_of_last_name:])
movie = "The Hangover"
print("My favorite movie is {}.".format(movie)) #placeholder
def favorite_book(title, author):
fav = "My favorite book is \"{}\", which is written by {}.".format(title,author)
return fav
print(favorite_book("Hitchhiker's Guide to the Galaxy", "Douglas Adams"))
print()
#Dictionaries
print("Dictionaries are keys and values:")
drinks = {"White Russian": 7,"Old Fashioned":10,"Lemon Drop":8,"Buttery Nipple":6} #drink:cost
print(drinks)
employees = {"Finance": ["Bob","Linda","Tina"], "IT": ["Gene","Louise", "Teddy"], "HR": ["Jimmy Jr.", "Mort"]}
print(employees)
employees["Legal"] = ["Mr. Frond"] #add new key:value pair
print(employees)
employees.update({"Sales": ["Andie", "Ollie"]})
print(employees)
drinks['White Russian'] = 8
print(drinks)
print(drinks.get("White Russian"))
print(drinks.get("DNE")) #getting a nonexistent entry returns None
#Lists and Dictionaries
movies = ["a", "b", "c", "d", "e"]
person = ["Heath", "Bob","Jon","Tiger"]
combined = zip(movies, person)
movie_dictionary = {key: value for key, value in combined}
print(movie_dictionary)
Last updated
Was this helpful?