python字符串、元祖、列表(有代码有注释)

梦里梦外; 2022-06-16 04:11 236阅读 0赞
  1. 通过直接运行代码看结果,体会一下python基本数据类型的用法。
  2. 请注意看代码注释。
  3. ======python代码开始======
  4. print '\n======="字符串"操作======='
  5. # 对字符串乘以N, 表示此字符串重复N次
  6. print "==" *10
  7. s1 = "hello \r" # \r是python里的回车符
  8. s2 = r"hello \r" # r"xxxxx" 原样输出双引号里的内容
  9. s3 = "你好"
  10. s4 = u"你好"
  11. print s1
  12. print s2
  13. print type(s3),s3 #str型
  14. print type(s4),s4 #unicode型
  15. # 字符串切片
  16. string = "Tony_仔仔"
  17. print "'Tony_仔仔'的前4个字:\t",string[:4]
  18. print "生成泪奔表情:\t", string[0]+string[4]+string[0]
  19. print "\n=======(元祖)操作======="
  20. """
  21. 定义一个元祖序列. 元祖特性是:一旦定义就不可变,即不再允许改变元祖本身或元祖内的元素!
  22. 元祖,字符串,列表都属于序列.
  23. 序列特性:有序的, 能按照下标范围操作序列中的元素(此操作也成为切片操作)
  24. """
  25. tp = (1, 2, 3, 4, 5, "abcde", "hello")
  26. print tp[1:] # 切片操作: 从下标1切到最后一个元素
  27. print tp[1:len(tp)]
  28. print tp[:-2] # 切片规则: 下标以0开始; 包含开始下标,不包含结束下标
  29. print "reverse tuple with step of 3: ",tp[::-3]
  30. print "reverse tuple with step of 1: ", tp[::-1]
  31. print "\n=======列表操作======="
  32. # 把元祖类型强制转行成列表类型
  33. a_list= list(tp)
  34. if type(a_list) == type([1,2,3]): # 若是列表类型则打印
  35. print (a_list)
  36. print"遍历列表:"
  37. for e in a_list: print e, # 加逗号表示不换行打印
  38. b_list = (a_list)
  39. print "\n b_list所有元素:\t",b_list
  40. print "before del b_list[1]:\t", b_list
  41. del b_list[1] # python 3.X可以删除列表中的元素,python 2.x不支持
  42. print "after del b_list[1]:\t",b_list
  43. print "'hello' first index in b_list: ",b_list.index("hello") # 返回指定元素的第一次出现的索引
  44. print "after del b_list[b_list]:\t", b_list
  45. tp2 = (0,"tony"), (1, "kid"), (2, "kid")
  46. b = dict(tp2)
  47. if type(b) == type({"a":10}):
  48. print b
  49. # tp2_2 = reversed(tp2)
  50. tp2_3 = tp2[::-1]
  51. for e in tp2_3: print e, # 与tp2_2的结果一样
  52. ======python代码结束======
  53. 代码运行结果:
  54. ======="字符串"操作=======
  55. ====================
  56. hello
  57. hello \r
  58. <type 'str'> 你好
  59. <type 'unicode'> 你好
  60. 'Tony_仔仔'的前4个字: Tony
  61. 生成泪奔表情: T_T
  62. =======(元祖)操作=======
  63. (2, 3, 4, 5, 'abcde', 'hello')
  64. (2, 3, 4, 5, 'abcde', 'hello')
  65. (1, 2, 3, 4, 5)
  66. reverse tuple with step of 3: ('hello', 4, 1)
  67. reverse tuple with step of 1: ('hello', 'abcde', 5, 4, 3, 2, 1)
  68. =======列表操作=======
  69. [1, 2, 3, 4, 5, 'abcde', 'hello']
  70. 遍历列表:
  71. 1 2 3 4 5 abcde hello
  72. b_list所有元素: [1, 2, 3, 4, 5, 'abcde', 'hello']
  73. before del b_list[1]: [1, 2, 3, 4, 5, 'abcde', 'hello']
  74. after del b_list[1]: [1, 3, 4, 5, 'abcde', 'hello']
  75. 'hello' first index in b_list: 5
  76. after del b_list[b_list]: [1, 3, 4, 5, 'abcde', 'hello']
  77. {0: 'tony', 1: 'kid', 2: 'kid'}
  78. (2, 'kid') (1, 'kid') (0, 'tony')

发表评论

表情:
评论列表 (有 0 条评论,236人围观)

还没有评论,来说两句吧...

相关阅读