Python Examples
Dave Braunschweig
Strings
# This program demonstrates string functions. def main(): string = "Hello" print("string: " + string) print("string.lower(): " + string.lower()) print("string.upper(): " + string.upper()) print("string.find('e'): " + str(string.find('e'))) print("len(string): " + str(len(string))) print("string.replace('H', 'j'): " + string.replace('H', 'j')) print("string[::-1]: " + string[::-1]) print("string[2:4]: " + string[2:4]) print("string.strip('H'): " + string.strip('H')) name = "Bob" value = 123.456 print("string.format(): {0} earned ${1:.2f}".format(name, value)) main()
Output
string: Hello string.lower(): hello string.upper(): HELLO string.find('e'): 1 len(string): 5 string.replace('H', 'j'): jello string[::-1]: olleH string[2:4]: ll string.strip('H'): ello string.format(): Bob earned $123.46
Files
# This program demonstrates reading a text file with exception handling. # # References: # https://en.wikibooks.org/wiki/Python_Programming def read_file(filename): try: with open(filename, "r") as file: for line in file: line = line.strip() print(line) except Exception as exception: print(exception) def main(): filename = "temperature.txt" read_file(filename) main()
Output
Celsius,Fahrenheit 0,32 10,50 20,68 ... 80,176 90,194 100,212