#!/usr/bin/env python # coding: utf-8 # # Strings # - string is a compound data type; sequence of characters # - can work with string as a single thing # - string variables are objects with their own attributes and methods # - help(str) to see all the methods # - commonly used methods: upper(), lower(), swapcase(), capitalize(), endswith(), isdigit(), find(), center(), count(), split(), etc. # In[ ]: help(str) # In[ ]: ss = "Hello there beautiful World!" tt = ss.upper() print(tt) print(tt.capitalize()) alist = tt.split() print(alist) # In[ ]: # examples of some methods ss.count('o') ss[0] = 'h' # In[ ]: # write a program to evaluate math operations # 2+2 # 3*3 eval('2+2') eval('print ("hello")') # ## working with the parts of a string # - string can be sliced using [index] or [inclStartIndex:ExclEndIndex:step] bracket operator # - negative indices are allowed - quick palindrome example # - string is immutable # - len() built-in function returns the length of a string # In[ ]: # examples s = "Pirates of the Caribbean" # print just the pirates #print(len(s[0:7])) # print the #print(s[-1:]) theIndex = s.find("the") print(theIndex) print(s[theIndex:theIndex+4]) # print Caribbean - hint use find function print(s[:]) print(s[1:]) print(s[-1::-2]) # In[ ]: lastSpace = s.rfind(' ') print(lastSpace) # In[ ]: a= "rarj" print ('palindrome') if a==a[::-1] else print('not palindrome') # In[ ]: s = "Pirates of the Caribbean." print(s[len(s)-1]) # ## string traversal using for and while loop # In[ ]: # example for loop for i in range(len(s)): print(s[i], end=' ') # In[ ]: for c in s: print(c, end=' ') # In[ ]: someStr = """afAdf@#456'"""" # In[ ]: # example while loop # In[ ]: i = 0 while i < len(s): print(s[i], end= ' ') i += 1 # ## string comparison # - strings can be compared # - compares lexicographically (ascii values) # # In[ ]: print(ord('a')) print(ord('A')) # In[18]: # e.g. print("apple" == "Apple")# false print("apple" >= "ball") # false print("apple" >= "Apple") # true # In[19]: print("apple" == "Apple") # false # ## in and not in operators # - help quickly test for membership # In[20]: print("p" in "apple") print("pe" in "apple") print("aple" not in "apple") # ## cleaning up strings # - remove punctuations # In[34]: # create a new string removing punctuations from the following string # string module ss = '"Well, I never did!", said Alice.' print(ss) # In[22]: print(ord('a')) # In[23]: newStr = '' for c in ss: if ord(c) == ord(' '): newStr += c elif ord(c) >= ord('A') and ord(c) <= ord('Z'): newStr += c elif ord(c) >= ord('a') and ord(c) <= ord('z'): newStr += c print(newStr) # In[24]: newStr1 = newStr.lower() print(newStr1) # In[26]: words = newStr1.split() print(words) # In[27]: for w in words: print(w) # In[28]: import string help(string) # In[32]: print(string.punctuation) # In[35]: ss # In[36]: newStr = '' for c in ss: if c in string.ascii_lowercase: newStr += c elif c in string.ascii_uppercase: newStr += c elif c == ' ': newStr += ' ' print(newStr) print(newStr.lower()) # In[40]: def cleanup(someStr): newStr = '' for c in someStr: if c.islower(): newStr += c elif c.isupper(): newStr += c elif c.isspace(): newStr += c return newStr # In[43]: s = cleanup(ss) print(s) # In[37]: help(str) # ## string formatting # - format method # - use {} as replacement field # - numbers in curly braces are optional; determine which argument gets substituted # - each of the replace fields can also contain a format specification # - < left alignment, > right, and ^ center, e.g. {1:<10} # - 10 is width # - type conversion such as f for float (.2f two decimal places), x for hex, etc. # In[44]: name = "Arthur" age = 25 s1 = "His name is {}!".format(name) print(s1) # In[46]: # note age and name are provided in reverse order print("His name is {1} and {1} is {0} years old.".format(age, name)) # In[48]: n1 = 4 n2 = 5 s3 = "2**10 = {0} and {1} * {2} = {3:.2f}".format(2**10, n1, n2, n1 * n2) print(s3) # In[49]: n1 = "Paris" n2 = "Whitney" n3 = "Hilton" print("Pi to three decimal places is {0:.3f}".format(3.1415926)) print("123456789 123456789 123456789 123456789 123456789 123456789") print("|||{0:<15}|||{1:^15}|||{2:>15}|||Born in {3}|||" .format(n1,n2,n3,1981)) print("The decimal value {0} converts to hex value {0:x}" .format(123456)) # In[50]: letter = """ Dear {0} {2}. {0}, I have an interesting money-making proposition for you! If you deposit $10 million into my bank account, I can double your money ... """ print(letter.format("Paris", "Whitney", "Hilton")) print(letter.format("Bill", "Warren", "Jeff")) # In[51]: layout = "{0:>4}{1:>6}{2:>6}{3:>8}{4:>13}{5:>24}" print(layout.format("i", "i**2", "i**3", "i**5", "i**10", "i**20")) for i in range(1, 11): print(layout.format(i, i**2, i**3, i**5, i**10, i**20)) # ## exercises # # 1 print a neat looking multiplication table like this: #
# 1 2 3 4 5 6 7 8 9 10 11 12 # :-------------------------------------------------- # 1: 1 2 3 4 5 6 7 8 9 10 11 12 # 2: 2 4 6 8 10 12 14 16 18 20 22 24 # 3: 3 6 9 12 15 18 21 24 27 30 33 36 # 4: 4 8 12 16 20 24 28 32 36 40 44 48 # 5: 5 10 15 20 25 30 35 40 45 50 55 60 # 6: 6 12 18 24 30 36 42 48 54 60 66 72 # 7: 7 14 21 28 35 42 49 56 63 70 77 84 # 8: 8 16 24 32 40 48 56 64 72 80 88 96 # 9: 9 18 27 36 45 54 63 72 81 90 99 108 # 10: 10 20 30 40 50 60 70 80 90 100 110 120 # 11: 11 22 33 44 55 66 77 88 99 110 121 132 # 12: 12 24 36 48 60 72 84 96 108 120 132 144 ## 2 write a program that calculates number of tirals required to guess a 3 digit passcode 777 (starting from 000, 001, 002, 003, 004, 005..., 010, etc.) using some brute force technique.