1 s = "Hello" 2 s += " world!" 3 print s # Hello world! 4 print len(s) # 12 5 print s[:5] # Hello 6 print s[5:] # world! 7 print s[1:10:2] # el ol 8 print s[10:1:-2] # drwol 9 print s.find("w") # 6 10 print s.find("w", 7) # -1 11 print s.find("w", 0, 6) # -1 12 print s.index("o") # 4 13 print s.rfind("o") # 7 14 print s.rfind("o", 7) # 7 15 print s.rfind("o", 8) # -1 16 print s.rfind("o", 0, 7) # 4 17 18 try: 19 print s.index("p") # should raise an exception 20 except ValueError, exc: 21 print 's.index("p"): value is not appropriate', exc.value 22 23 print s.startswith("Hello") # True 24 print s.startswith("world") # False 25 print s.endswith("world!") # True 26 print s.endswith("Hello") # False 27 28 s2 = "Hello worlds!" 29 print s2 # Hello worlds! 30 print len(s2) # 13 31 print s < s2 # True 32 print s <= s2 # True 33 print s == s2 # False 34 print s != s2 # True 35 print s >= s2 # False 36 print s > s2 # False 37 38 print s[0] # H 39 print s[-1] # ! 40 41 print ord(s[0]) # 72 42 43 try: 44 print ord(s) # should raise an exception 45 except ValueError, exc: 46 print "ord(s): value is not appropriate", exc.value 47 48 l = ["Hello", "world!"] 49 s3 = " ".join(l) 50 print s3 # Hello world! 51 print len(s3) # 12 52 53 s4 = "".join(l) 54 print s4 # Helloworld! 55 print len(s4) # 11 56 57 s5 = "--".join(l) 58 print s5 # Hello--world! 59 print len(s5) # 13 60 61 print "# hash(s):", 62 print hash(s) 63 print "# hash(s2):", 64 print hash(s2) 65 print "# hash(s3):", 66 print hash(s3) 67 print "# hash(s4):", 68 print hash(s4) 69 print "# hash(s5):", 70 print hash(s5) 71 72 # Test multiplication of strings. 73 74 s6 = "abc" 75 print s6 * -1 # 76 print s6 * 0 # 77 print s6 * 1 # abc 78 print s6 * 2 # abcabc 79 print -1 * s6 # 80 print 0 * s6 # 81 print 1 * s6 # abc 82 print 2 * s6 # abcabc 83 84 # Test splitting of strings. 85 86 s7 = "Hello...\n world,\n planet,\n globe." 87 print s7.split() # ["Hello...", "world,", "planet,", "globe."] 88 print s7.split(maxsplit=2) # ["Hello...", "world,", "planet,\n globe."] 89 print s7.split("\n") # ["Hello...", " world,", " planet,", " globe."]