Advertisement
oldmagi

chapter 6

Aug 21st, 2012
223
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.33 KB | None | 0 0
  1. #Exercise 6.1 Write a while loop that starts at the last character in the string and works its way backwards to the first character in the string, printing each letter on a separate line, except backwards.
  2.  
  3. prog_lang='python3'
  4. i=len(prog_lang)
  5. while i>0:
  6.     i-=1
  7.     print(prog_lang[i],'\n')
  8. ------------------------------------------------------------------------------------------------
  9. #Exercise 6.2 Given that fruit is a string, what does fruit[:] mean?
  10.  
  11. fruit='string'
  12. print(fruit[:])
  13. #full string
  14. ------------------------------------------------------------------------------------------------
  15. #Exercise 6.3 Encapsulate this code in a function named count, and generalize it so that it accepts the string and the letter as arguments.
  16.  
  17. def count(word,l):
  18.     count = 0
  19.     for letter in word:
  20.         if letter == l:
  21.             count = count + 1
  22.     print(count)
  23.  
  24.  
  25. userword='banana'
  26. userletter='a'
  27. count(userword,userletter)
  28. ------------------------------------------------------------------------------------------------
  29. #Exercise 6.4 There is a string method called count that is similar to the function in the previous exercise. Read the documentation of this method at docs.python.org/library/string.html and write an invocation that counts the number of times the letter a occurs in 'banana'.
  30.  
  31. str_ing='banana'
  32. let_ter='a'
  33. print(str_ing.count(let_ter))
  34. ------------------------------------------------------------------------------------------------
  35. #Exercise 6.5
  36. str_ing='X-DSPAM-Confidence: 0.8475'
  37. str_ing=str_ing[str_ing.find(':')+1:]
  38. print('Converted string to float :',float(str_ing))
  39. print('Conversion check:',type(str_ing))
  40. ------------------------------------------------------------------------------------------------
  41. #Excersice 6.6 string methods
  42. word="orange"
  43. print('str.upper=',word.upper())
  44. print('str.lower=',word.lower())
  45. print('str.capitalize=',word.capitalize())
  46. a="chocolate"
  47. print('count of letter o in string a is:',a.count('o'))
  48. b='hello!'
  49. print('str.encode=',b.encode(encoding='utf-8'))
  50. print('str.find=',a.find('o',1,3))
  51. print("1+1 is {}".format(1+1))
  52. print('str.replace =',b.replace('!',' josh',3))
  53. print(a)
  54. print('str.join=',b.join('12345'))
  55. c=" how are you?  \n"
  56. print('str.strip',c.strip())
  57. print('str.swapcase',c.swapcase())
  58. d="...,I am fine so.,"
  59. print('str.lstrip is',d.lstrip('hello.,'))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement