Python中元组和字符串代码演示(可运行)

"""
首先,列表是可以修改的,如果想要传递的信息不被篡改,列表就不合适了,元组和列表一样,都是可以封装多个,不同类型的元素在内
但最大区别在于,元组一旦形成,就不可以被修改啦,所以,当我们需要在程序内封装数据,又不希望封装的数据被篡改,那么元组就非常合适啦。

"""

# 定义元组
tuple_01 = (1,2,3,4,5,6)
# 定义一个空元组
tuple_02 = ()
print(tuple_01)
print(f"元组为:{tuple_02},空元组的类型是:{type(tuple_02)}")


# 元组的嵌套
tuple_03 = ('赵','钱','孙','李',100,'Tom')
tuple_04 = (tuple_01,tuple_03)
print(tuple_04[0][0])
print("嵌套的元组为:",tuple_04)

# 元组的查找方法: 使用[.index(元素)]方法,找到元素所在的下标。
tuple_03 = ('赵','钱','孙','李',100,'Tom')
index = tuple_03.index(100)
print("元素100的下标是:",index)

# 元组中单个元素的统计方法使用[.count(元素)]方法
tuple_05 = (1,1,1,1,1,1,2,2,3,3,4,4,5,5)
count = tuple_05.count(1)
print(count)


# 元组中统计所有元素的个数
tuple_05 = (1,1,1,1,1,1,2,2,3,3,4,4,5,5)
num  = len(tuple_05)
print(num)


# 元组的while循环遍历
tuple_03 = ('赵','钱','孙','李',100,'Tom')
index = 0
while index<len(tuple_03):
    print(tuple_03[index],end=' ')
    index+=1

print()
# 使用for循环进行遍历
tuple_03 = ('赵','钱','孙','李',100,'Tom')
for x in tuple_03:
    print(x,end='   ')

"""
字符串:
同元组一样,字符串是一个:无法修改的数据容器,所以无法对字符串进行增删等操作。
"""
print()

# 定义一个字符串
sentence = "hello,i will carry you"

# 通过下标索引取值
print(sentence[0])
print(sentence[1])
print(sentence[2])
print(sentence[3])

# 使用【.index(元素)】方法
value = sentence.index('w')
print("w所在的下标为:",value)

# 使用replace方法,进行字符串替换【.replace(str1,str2)】,将字符串内的全部字符串1,替换成字符串2
# (注意这不是修改字符串本身,而是得到一个新的字符串。)
sentence = "hello,i will carry you"
sentence_02 = sentence.replace('o','m')
print("替换后的句子为:",sentence_02)

# 使用split方法进行字符串的分割,【.split(分割字符串)】,按照指定的分割字符串,将字符串划分为多个字符串,
# 并存入列表对象中,(字符串本身不变而是得到一个列表对象)
sentence = "hello i will carry you"
sentence_03 = sentence.split(' ')
print(f"输出原本字符串:{sentence},输出经split分割后的列表:{sentence_03},打印分割后对象的类型:{type(sentence_03)}")

# 字符串规整操作:使用strip()方法,只能取出字符串中最前和最后
# 去掉字符串中前后空格(不传入参数)
sentence = "   hello i will carry you     "
result = sentence.strip()
print(f"打印原来的字符串:{sentence},打印经过规整操作之后的字符串:{result},打印规整之后结果的类型:{type(result)}")

# 去掉前后指定字符串(如传入的是”12“,其实就是”1“和”2“都会被移除,是按照单个字符的)
sentence = "1212121hello i will carry you2121212"
result = sentence.strip("12")
print(f"打印原来的字符串:{sentence},打印经过规整操作之后的字符串:{result},打印规整之后结果的类型:{type(result)}")

# 统计字符串中某个字符出现的次数
sentence = "hello i will carry you"
num = sentence.count('l')
print(f"字符串中l出现的次数是:{num}次")

# 统计字符串中一共有多少个字符
sentence = "hello i will carry you"
num = len(sentence)
print("字符串中个数共有:",num)
  • 7
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

代替人格

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值