python之元组笔记

本文详细介绍了Python中的元组,包括定义、读取元素、切片、检索等操作,并通过实例演示了字符串的find、replace、split和join方法。此外,还展示了如何统计字符串中特定字符出现的次数以及处理输入的单词和字符计数。
摘要由CSDN通过智能技术生成
#元组(tuple)属于不可改变序列,任何方法都修改不了
#元组用()

#1.定义
a_tuple=('python','java','c','HTML')
b_tuple=(1,2,(3.0,'hello world!'))  #元组中嵌套了元组类型
c_tuple=('wade',3.0,81,['bosh','c'])  #元组中嵌套了列表类型
d_tuple=()  #空元祖
print(a_tuple)
print(b_tuple)
print(c_tuple)
print(d_tuple)

#为了避免与数学上的()产生歧义,创建元组时要在元素的后面加',',接下来对比一下
x=(1)
y=(1,2)
print(x)
print(y)

#2.读取元素
print(a_tuple[1])
print(a_tuple[-1])
#a_tuple[6]超出元组长度

#3.元组切片得到一个新的元组
print(a_tuple[1:3])
print(a_tuple[::2])

#4.检索元组
#1)index()获取指定元素首次出现的下标
print(a_tuple.index('c'))
#2)count()统计元组中指定元素出现的次数
print(a_tuple.count('c'))
#3)使用in运算符检索某个元素是否在元组,在True,不在False
print('c' in a_tuple)
print(1 in a_tuple)

#5.删除元组(删除之后元组中将没有,再次访问会出错)
#del a_tuple

#6字符串
#1)find()
s1="beijing xi'an tianjin beijing chongqing"
print(s1.find('beijing'))
print(s1.find('beijing',3))
print(s1.find('tianjin',3,20))

#2)replace()字符串替换,第三个参数表示替换不能超过的次数
s2="this is string example.this is string example."
s2.replace("is","was")
print(s2.replace("is","was"))
print(s2.replace("is","was",2))

#3)split()字符串分离
s3="beijing,xi'an,tianjin,beijing,chongqing"
print(s3.split(','))
print(s3.split('a'))

#4)join()字符串连接
#sep.join(sequence)   sep表示分隔符,sequence表示要链接的元素序列
s4=["beijing","xi'an","tianjin","beijing","chongqing"]
sep="-->"
str=sep.join(s4)
print(str)

s5=("hello","world")
sep=""
print(sep.join(s5))

#举个栗子
#从键盘上输入五个英文单词,输出其中以元音字母开头的单词

str='AEIOUaeiou'
l_list=[]
'''for i in range(0,5):
    word=input("请输入英文单词:")
    l_list.append(word)
print("输入的五个英文单词是:",l_list)
print("首字母是元音字母开头的单词是:")
for i in range(0,5):
    for ch in str:
        if l_list[i][0] == ch:
            print(l_list[i])
            break'''


#再来一个栗子
#输入一段字符,统计其中的单词的个数,单词之间用空格分隔
'''str=input("请输入一串字符:")
flag=0
count=0

for c in str:
    if c == " ":
        flag=0
    else:
        if flag == 0:
            flag = 1
            count += 1
print("共有%d个单词"%count)'''

#最后一个例子
#输入一行字符,分别统计其中的英文字母,空格,数字和其他字符的个数
L_list=list(input("请输入一行字符:"))
letter=[]
space=[]
number=[]
other=[]

for i in range(len(L_list)):
    if ord(L_list[i]) in range(65,91) or ord(L_list[i]) in range(97,123):
        letter.append(L_list[i])
    elif L_list[i] in " ":
        space.append(L_list[i])
    elif ord(L_list[i]) in range(48,58):
        number.append(L_list[i])
    else:
        other.append(L_list[i])

print("英文字母个数为:%s"%len(letter))
print("空格个数为:%s"%len(space))
print("数字个数为:%s"%len(number))
print("其他字符个数为:%s"%len(other))

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值