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

 
 
通过直接运行代码看结果,体会一下python基本数据类型的用法。
请注意看代码注释。
 
======python代码开始======

 

print '\n======="字符串"操作======='
# 对字符串乘以N, 表示此字符串重复N次
print "==" *10

s1 = "hello \r"  # \r是python里的回车符
s2 = r"hello \r"  # r"xxxxx" 原样输出双引号里的内容
s3 = "你好"
s4 = u"你好"
print s1
print s2
print type(s3),s3   #str型
print type(s4),s4   #unicode型

# 字符串切片
string = "Tony_仔仔"
print "'Tony_仔仔'的前4个字:\t",string[:4]
print "生成泪奔表情:\t", string[0]+string[4]+string[0]


print "\n=======(元祖)操作======="
"""
    定义一个元祖序列. 元祖特性是:一旦定义就不可变,即不再允许改变元祖本身或元祖内的元素!
    元祖,字符串,列表都属于序列.
    序列特性:有序的, 能按照下标范围操作序列中的元素(此操作也成为切片操作)
"""
tp = (1, 2, 3, 4, 5, "abcde", "hello")
print tp[1:]  # 切片操作: 从下标1切到最后一个元素
print tp[1:len(tp)]
print tp[:-2]   # 切片规则: 下标以0开始; 包含开始下标,不包含结束下标
print "reverse tuple with step of 3: ",tp[::-3]
print "reverse tuple with step of 1: ", tp[::-1]


print "\n=======列表操作======="
# 把元祖类型强制转行成列表类型
a_list= list(tp)
if type(a_list) == type([1,2,3]):   # 若是列表类型则打印
    print (a_list)

print"遍历列表:"
for e in a_list: print e,   # 加逗号表示不换行打印

b_list = (a_list)
print "\n b_list所有元素:\t",b_list
print "before del b_list[1]:\t", b_list
del b_list[1]  # python 3.X可以删除列表中的元素,python 2.x不支持
print "after del b_list[1]:\t",b_list

print "'hello' first index in b_list: ",b_list.index("hello")  # 返回指定元素的第一次出现的索引
print "after del b_list[b_list]:\t", b_list

tp2 = (0,"tony"), (1, "kid"), (2, "kid")
b = dict(tp2)
if type(b) == type({"a":10}):
    print b

# tp2_2 = reversed(tp2)
tp2_3 = tp2[::-1]
for e in tp2_3: print e,    # 与tp2_2的结果一样

 

 

======python代码结束======

 

代码运行结果:
======="字符串"操作=======
====================
hello 
hello \r
<type 'str'> 你好
<type 'unicode'> 你好
'Tony_仔仔'的前4个字:	Tony
生成泪奔表情:	T_T


=======(元祖)操作=======
(2, 3, 4, 5, 'abcde', 'hello')
(2, 3, 4, 5, 'abcde', 'hello')
(1, 2, 3, 4, 5)
reverse tuple with step of 3:  ('hello', 4, 1)
reverse tuple with step of 1:  ('hello', 'abcde', 5, 4, 3, 2, 1)


=======列表操作=======
[1, 2, 3, 4, 5, 'abcde', 'hello']
遍历列表:
1 2 3 4 5 abcde hello 
 b_list所有元素:	[1, 2, 3, 4, 5, 'abcde', 'hello']
before del b_list[1]:	[1, 2, 3, 4, 5, 'abcde', 'hello']
after del b_list[1]:	[1, 3, 4, 5, 'abcde', 'hello']
'hello' first index in b_list: 5
after del b_list[b_list]:	[1, 3, 4, 5, 'abcde', 'hello']
{0: 'tony', 1: 'kid', 2: 'kid'}
(2, 'kid') (1, 'kid') (0, 'tony') 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值