Experimenting with Strings (Python)

Please support our Python advertiser: Programming Forums - DaniWeb Sister Site
vegaseat vegaseat is offline Offline Jan 23rd, 2005, 12:40 pm |
0
There are some pretty fancy things you can do with strings in Python. You can append, convert, justify, join, split, slice, and list selected files of a folder. I just give you a small sample here.
Quick reply to this message  
Python Syntax
  1. # a look at strings and methods
  2. # tested with Python23 vegaseat 23jan2005
  3.  
  4. print "Fill an empty string:"
  5. empty_string = ""
  6. for k in range(65, 91):
  7. empty_string += chr(k)
  8. print empty_string
  9.  
  10. print "\nOriginal string (California humor):"
  11. s = "She has 8 body piercings and none are visible"
  12. print s
  13.  
  14. print "\nSeparate string at any whitespace to a list of words:"
  15. sL = []
  16. sL = s.split()
  17. print sL
  18. print "\nShow item 4 on the list (lists are zero based):"
  19. print sL[4]
  20.  
  21. # iterate through the list and also show item numbers
  22. print "\nIterate (walk) through the list:"
  23. for k in range (len(sL)):
  24. print k, sL[k]
  25.  
  26. # print words and length
  27. print "\nAgain this time show words and ( length ):"
  28. for word in sL:
  29. print word, " (", len(word), ")"
  30.  
  31. # append one more word
  32. print "\nAdd one more word to the end:"
  33. sL.append("yet!")
  34. print sL
  35.  
  36. print "\nJoin the list of words to form a string again:"
  37. # single space = " " as a delimiter
  38. print " ".join(sL) + '\n'
  39.  
  40. # a string can be enclosed in " or ' so if you want to
  41. # use " as part of the string, enclose it with '
  42. s2 = '"How to Serve Your Fellow Man"'
  43. s3 = "Cannibal's recipe book:"
  44.  
  45. # left justify string s3 and pad with 2 spaces past its length
  46. # then concatenate ( use + ) with string s2
  47. print "Concatenate two strings, leftjustify and pad first string:"
  48. print s3.ljust(len(s3) + 2) + s2 + '\n'
  49.  
  50. s4 = "hippopotamus"
  51. print "full string = ", s4
  52.  
  53. print "spell/space it:"
  54. for char in s4:
  55. print char,
  56. print
  57.  
  58. print "count the characters:"
  59. # create an empty dictionary
  60. charCount = {}
  61. for char in s4:
  62. charCount[char] = charCount.get(char, 0) + 1
  63. print charCount
  64.  
  65. print "full string = ", s4
  66. print "first char = ", s4[0]
  67. print "last char = ", s4[-1]
  68. """
  69. now for something completely different, slicing ...
  70. [starting-at-index : but-less-than-index [ : step]]
  71. start defaults to 0, end to len(sequence), step to 1
  72. """
  73. print "first 2 char = ", s4[0:2]
  74. print "next 2 char = ", s4[2:4]
  75. print "last 2 char = ", s4[-2:]
  76. print "exclude first 3 char = ", s4[3: ]
  77. print "exclude last 4 char = ", s4[:-4]
  78. print "reverse the string = ", s4[::-1]
  79. print "the whole word again = ", s4
  80. # [start:end:step]
  81. print "spell skipping 2 char = ", s4[::2]
  82.  
  83. print "concatenate 3 strings = ", s4 + s4 + s4
  84. # same result
  85. print "simply multiply by 3 = ", s4 * 3
  86. # prints 50 dashes
  87. print '-' * 50
  88.  
  89. print
  90.  
  91. print "Convert an integer or float to a string with repr() or str():"
  92. num1 = 3.14
  93. print "num1 =", num1
  94. print "repr(num1) = %s" % repr(num1)
  95. print "str(num1) = %s" % str(num1)
  96. print
  97. str1 = str(num1)
  98. print "Convert numeric string back to an integer or float with eval():"
  99. num2 = eval(str1)
  100. print "eval(str1) =", eval(str1)
  101. print "type(eval(str1)) =", type(eval(str1))
  102. print "If you know the type, you can use int(str1) or float(str1)"
  103. print
  104. print "An added bonus, function int() has a base option:"
  105. print "binary to decimal int('1111', 2) =", int('1111', 2)
  106. print "hexadecimal to decimal int('FF', 16) =", int('FF', 16)
  107. print
  108. print "One more bonus, eval() can evaluate a math expression string:"
  109. print "eval('3 * 4 + 2') =", eval('3 * 4 + 2')
  110.  
  111. print
  112.  
  113. print "Comparing strings:"
  114. print "cmp('mouse', 'mouse') = ", cmp('mouse', 'mouse')
  115. print "cmp('mouse', 'louse') = ", cmp('mouse', 'louse')
  116. print "cmp('louse', 'mouse') = ", cmp('louse', 'mouse')
  117.  
  118. print
  119.  
  120. # make your own words, a little character fun ...
  121. str1 = 'Aack' # 'Auck' might be a temptation
  122. print "Replace A in %s with other letters:" % str1
  123. # go from B to Z
  124. for b in range(66, 91):
  125. ch = chr(b)
  126. if ch == 'Q': # special case Q, use Qu
  127. ch = ch + 'u'
  128. print str1.replace('A', ch)
  129.  
  130. print
  131.  
  132. # how to create a multiline string ...
  133. print "This is a multiline string:"
  134. mlStr = """Noses are running.
  135. Feet are smelling.
  136. Park on driveway.
  137. Drive on parkway.
  138. Recite at a play.
  139. Play at a recital.
  140. """
  141. print mlStr
  142. print "Show the line that starts with Park:"
  143. # find Park index/position
  144. pos1 = mlStr.find("Park")
  145. # find index of the end of that line
  146. pos2 = mlStr.find("\n", pos1)
  147. # slice the line from the string
  148. line = mlStr[pos1:pos2]
  149. print line
  150.  
  151. print
  152.  
  153. # if you just want to see if a substring is there ...
  154. subStr = 'smell'
  155. if subStr in mlStr:
  156. print "Found substring '%s'" % subStr
  157.  
  158. print
  159.  
  160. print "There are", mlStr.count('a'), "'a' in the multiline string."
  161. print "They are at index:"
  162. index = mlStr.find('a') # find first
  163. print index
  164. while index != -1: # look for more
  165. index = mlStr.find('a', index + 1)
  166. if index > 0:
  167. print index
  168.  
  169. print
  170.  
  171. print "Extract a substring located between two given substrings, here the quotes:"
  172.  
  173. def extract(text, sub1, sub2):
  174. """extract a substring between two substrings sub1 and sub2 in text"""
  175. return text.split(sub1)[-1].split(sub2)[0]
  176.  
  177. str3 = 'I bought the "Python Cookbook" and could not find one single recipe about cooking the slithery beast!'
  178. # notice that here beginning and trailing spaces can be included with the quotes
  179. str4 = extract(str3, ' "', '" ')
  180. print str3
  181. print str4
  182.  
  183. print
  184.  
  185. print "Line continuation (\) can also be used for long or multiline strings:"
  186. # combining three strings to one string
  187. # (ignores whitespace between strings)
  188. # (do not add a space right behind the \)
  189. str1 = "The alien wheezes, 'Darn, this is it. I will die now! \n"\
  190. "Tell my 2.4 million larvae that I esteem them ... \n"\
  191. "Good-bye, truculent universe.'"
  192. print str1
  193.  
  194. print
  195.  
  196. # file names are strings, so let's find them
  197. # find all the .py files in the working folder (path = '')
  198. import os # module needed for listdir()
  199. print "Add all the python files in the working folder to a list:"
  200. path = ''
  201. ext = '.py'
  202. filelist = []
  203. for filename in os.listdir(path):
  204. if filename.endswith(ext):
  205. filelist.append(filename)
  206.  
  207. # show the list
  208. print filelist
  209.  
  210. print "\nPrint the file list one item on a line:"
  211. # new line as delimiter
  212. print "\n".join(filelist)
  213.  
  214. print
  215.  
  216. # a function can have a documentation string
  217. def formatDollar(amount):
  218. "formatDollar(amount) returns a string with the amount formatted to $ currency"
  219. return "$%.2f" % amount
  220.  
  221. print "The function's documentation string:"
  222. print formatDollar.__doc__
  223. print
  224. print "For example", 123.9 * 0.0725,"formatted to", formatDollar(123.9 * 0.0725)
0
vegaseat vegaseat is offline Offline | Mar 15th, 2005
Corrected the mouse/louse mixup, sorry!
 
 

Message:


Similar Threads
Thread Tools Search this Thread



Tag cloud for Python
About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC