Python数据类型之 Str List Tuple

本文介绍了Python中的字符串操作,包括创建、访问、子字符串匹配等方法,同时涵盖了列表、元组等数据结构的基本用法及常见操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

字符串 String

字符串是 Python 中最常用的数据类型。我们可以使用引号('或")来创建字符串。

Python不支持单字符类型,单字符在 Python 中也是作为一个字符串使用。
Python访问子字符串,可以使用方括号来截取字符串,如下实例

var1 = 'Hello World!'
var2 = "Python Runoob"

print("var1[0]: ", var1[0])
print("var2[1:5]: ", var2[1:5])

var1[0]:  H
var2[1:5]:  ytho

字符串的方法 “str”

“”.index

匹配子字符串,并返回第一配置项的索引位置
a = "hello ! my name is chenhuaicong!!!"
print(a.index("my"))

8

“”.count

统计子字符串在匹配的次数
a = "hello ! my name is chenhuaicong!!!"
print(a.count("h"))

“”.replace

替换
a = "hello ! my name is chenhuaicong!!!"
print(a.replace("my","your"))

hello ! your name is chenhuaicong!!!

“”.strip

前后去空格
a = "  hello ! my name is chenhuaicong!!!  "
print(a.strip())

hello ! my name is chenhuaicong!!!

” “.join

(可迭代对象) 将新字符串加入到字符串中
a = "hello ! my name is chenhuaicong!!!"
print("-".join(a))

h-e-l-l-o- -!- -m-y- -n-a-m-e- -i-s- -c-h-e-n-h-u-a-i-c-o-n-g-!-!-!

“”.split

分割
a = "hello ! my name is chenhuaicong!!!"
print(a.split(" "))

['hello', '!', 'my', 'name', 'is', 'chenhuaicong!!!']

“”.format

字符串格式化
a = "hello ! my name is chenhuaicong!!!"
b = "the boy said: {0}".format(a)
print(b)

列表

列表是由一序列特定顺序排列的元素组成的。可以把字符串,数字,字典等都可以任何东西加入到列表中,日中的元素之间没有任何关系。列表也是自带下标的,默认也还是从0开始

列表的方法 list()

[].append

在列表的末尾添加新的对象
k = [1,2,3,4,5,6,7,1,23,45]
k.append("chenhuaicong")
print(k)

[1, 2, 3, 4, 5, 6, 7, 1, 23, 45, 'chenhuaicong']

[].count

统计列表中元素出现的次数
k = [1,2,3,4,5,6,7,1,5,23,45,5]

print(k.count(5))

3

[].extend

在列表的末尾追加另外一个列表
k = [1,2,3,4,5,6,7,1,5,23,45,5]
q = ["我","abc",4,6]
k.extend(q)
print(k)


[1, 2, 3, 4, 5, 6, 7, 1, 5, 23, 45, 5, '我', 'abc', 4, 6]

[].index

从列表中找出某个值第一个匹配项的索引位置
k = [1,2,3,4,5,6,7,1,5,23,45,5]
print(k.index(3))

2

[].insert

将对象插入列表
k = [1,2,3,4,5,6,7,1,5,23,45,5]
k.insert(3,"hello")
print(k)

[1, 2, 3, 'hello', 4, 5, 6, 7, 1, 5, 23, 45, 5]

[].pop

移除列表中的一个元素,默认是最后一个元素,并且返回改元素的值
k = [1,2,3,4,5,6,7,1,5,23,45,5]
print(k.pop())
print(k)

5
[1, 2, 3, 4, 5, 6, 7, 1, 5, 23, 45]
k = [1,2,3,4,5,6,7,1,5,23,45,5]
print(k.pop(5))
print(k)

6
[1, 2, 3, 4, 5, 7, 1, 5, 23, 45, 5]

[].remove

移除列表中某个值的第一匹配项
k = [1,2,3,4,5,6,7,1,5,23,45,5]
k.remove(5)
print(k)

[1, 2, 3, 4, 6, 7, 1, 5, 23, 45, 5]

[].reverse

反转列表中的元素
k = [1,2,3,4,5,6,7,1,5,23,45,5]
k.reverse()
print(k)

[5, 45, 23, 5, 1, 7, 6, 5, 4, 3, 2, 1]

[].sort

对原列表进行排序
k = [1,2,3,4,5,6,7,1,5,23,45,5]
k.sort()
print(k)

[1, 1, 2, 3, 4, 5, 5, 5, 6, 7, 23, 45]

元组

定义:Tuple就是不可变的list

元组tuple()

().index(x)

查找某元素,并返回该元素的索引位置
a = ("a","b","c","d","e","f","g")
print(a.index("c"))

2

().count(x)

统元素出现的次数
a = ("a","b","c","d","e","f","g","c")
print(a.count("c"))

2
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值