python基础-字符串str " "

字符串的定义和操作

字符串的特性:

元素数量 支持多个
元素类型 仅字符
下标索引 支持
重复元素 支持
可修改性 不支持
数据有序
使用场景

一串字符的记录场景

字符串的相关操作:

my_str = "itheima and itcast"
# 通过下标索引取值
value = my_str[2]
value2 = my_str[-12]
print(value)
print(value2)
# index方法
value = my_str.index("and")
print(f"查看索引位置:{value}")
# replace方法
new_my_str = my_str.replace("and","和")
print(f"将字符串{my_str},进行替换后得到:{new_my_str}")
# split方法 返回一个列表
my_str = "hello python itheima itcast"
my_str_list = my_str.split(" ")#利用空格进行分割
print(f"将字符串{my_str}进行split切分后得到:{my_str_list}")
# strip方法 去前后空格
my_str = " itheima and itcast "
print(my_str)
print(my_str.strip())
# strip(字符串)方法 去前后指定字符串
my_str = "aaaitheima and itcastaaaa"
print(my_str)
# 实际是a b c 依次去除
print(my_str.strip("abc"))
# rstrip() 函数,去除字符串右边的指定字符
print("3123".rstrip('3'),'') # 312 ''里面可以任意填数
# lstrip() 函数,去除字符串左边的指定字符
print("3123".lstrip('3'),'') # 123 ''里面可以任意填数
# 统计字符串中某字符串的出现次数,count
my_str = "itheima and itcast"
count = my_str.count("it")
print(f"出现次数:{count}")
# 统计字符串的长度:len()
num = len(my_str)
print(f"字符串的长度是:{num}")
# join() 方法用于将序列中的元素以指定的字符连接生成一个新的字符串。
print('abc'.join('123')) # 1abc2abc3
# Python startswith() 方法用于检查字符串是否是以指定子字符串开头,如果是则返回 True,否则返回 False。如果参数 beg 和 end 指定值,则在指定范围内检查。
str.startswith(str, beg=0,end=len(string));
# 遍历字符串
# 迭代
s1 = "123456"
for s in s1:
print(s)

 

posted @   0x1e61  阅读(8)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· 单线程的Redis速度为什么快?
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
点击右上角即可分享
微信分享提示