python:容器:字符串——常用操作

本文介绍了Python中对字符串的一些基本操作,包括通过下标访问字符,使用index方法查找字符位置,replace方法替换字符串内容,split方法按指定字符分割字符串成列表,strip方法去除首尾空白以及指定字符,count方法计算子字符串出现次数,len函数获取字符串长度,以及如何遍历字符串。
摘要由CSDN通过智能技术生成
字符串[下标]根据下标索引取出特定位置字符
字符串.index(字符串)查找给定字符的第一个匹配项的下标
字符串.replace(字符串1,字符串2)

将字符串内的全部字符串1,替换为字符串2

不会修改原字符串,而是得到一个新的

字符串.split(字符串)

按照给定字符串,对字符串进行分隔不会修改原字符串,

而是得到一个新的列表

字符串.strip()

字符串.strip(字符串)

移除首尾的空格和换行符或指定字符串
字符串.count(字符串)统计字符串内某字符串的出现次数
len(字符串)统计字符串的字符个数

下标

test1 = 'hello world'

字符串'hello wrold'   

h的下标为 0    e下标为1   依次类推     空格也是有下标的

反过来的话   d为-1    l为-2


通过下标输出字符串

test1 = 'hello world'
print(test1[0])     # 输出h

index

test1 = 'hello world'
print(test1.index("w"))   # 6
# 或者
index_1 = test1.index("d")
print(index_1)            # 10

replace

test1 = 'hello world'
test2 = test1.replace('l','a')
print(test2)    # heaao worad

 split

test1 = 'hello world'
test1_list = test1.split(" ")   # 通过 空格将其中的 字符串分割成列表
print(test1_list)       # ['hello', 'world']
print(test1_list[1])    # world

strip

test1 = ' hello world '
print(test1)  # 现在可以看到两侧有空格   ' hello world '
test2= test1.strip()
print(test2)    # hello world  经过处理  不仅空格会没    如果带有换行等 都会被去除
test3 = test2.strip("d")    # 去除两侧的d
print(test3)    # hello worl


count

test1 = ' hello world '
test2= test1.count("l") # 统计l出现的次数
print(test2)    # 3

 len

test1 = ' hello world '
print(len(test1))   # 13

遍历

test1 = ' hello world '
for a in test1:
    print(a)

 

如果不想让他换行

test1 = ' hello world '
for a in test1:
    print(a,end="")

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值