Python入门篇【字符串】

Python数据容器【字符串】


文章目录

  • Python数据容器【字符串】
  • 一、字符串定义
  • 二、字符串常见操作
    • [2.1 查找字符串下标索引值【index】](#2.1 查找字符串下标索引值【index】)
    • [2.2 字符串替换【replace】](#2.2 字符串替换【replace】)
    • [2.3 字符串分割【split】](#2.3 字符串分割【split】)
    • [2.4 字符串规整【strip】](#2.4 字符串规整【strip】)
      • [2.4.1 去前后空格](#2.4.1 去前后空格)
      • [2.4.2 去前后指定字符串](#2.4.2 去前后指定字符串)
    • [2.5 字符串中字符出现次数【count】](#2.5 字符串中字符出现次数【count】)
    • [2.6 字符串长度【len】](#2.6 字符串长度【len】)
    • [2.7 字符串遍历【while】](#2.7 字符串遍历【while】)
    • [2.7 字符串遍历【for】](#2.7 字符串遍历【for】)
  • 三、特点

提示:以下是本篇文章正文内容,下面案例可供参考

一、字符串定义

字符串是字符的容器,一个字符串可以存放多个字符,下标从0开始,从后向前下标从-1开始。
字符串是一个不可修改的数据容器,如果必须要修改,则会生成一个新的字符串。

python 复制代码
# 定义字符串

str_demo = "imzhangsans"
str_value = str_demo[0]
str_value2 = str_demo[-1]
print(str_value)
print(str_value2)

二、字符串常见操作

2.1 查找字符串下标索引值【index】

python 复制代码
# index查找
str_index = str_demo.index('z')
print(str_index)

2.2 字符串替换【replace】

将字符串中的字符1替换成字符2,然后生成一个新的字符串。

python 复制代码
#语法
字符串.replace(字符串1,字符串2)
python 复制代码
#字符替换
str_new_demo = str_demo.replace('s','q')
print(str_demo)
print(str_new_demo)

2.3 字符串分割【split】

按照指定的分隔符字符串,将字符串分为多个字符串,然后存入列表中。
字符串本身不变,而是得到一个新的列表对象。

python 复制代码
#字符串分割
str_list_split=str_demo.split('z')
print(str_list_split)

2.4 字符串规整【strip】

2.4.1 去前后空格

python 复制代码
# 字符串规整
str_demo_new = str_demo.strip(" ") #不传参数去除首尾空格
print(str_demo_new)

2.4.2 去前后指定字符串

python 复制代码
# 字符串规整
str_demo_new = str_demo.strip(" ") #不传参数去除首尾空格
str_demo_new2 = str_demo_new.strip("12") #传值,存在1和2的任何一位,去除
print(str_demo_new2)

2.5 字符串中字符出现次数【count】

python 复制代码
str_demo2 = "12 imzhanzgszans 12"
count = str_demo2.count('z')
print(count)

2.6 字符串长度【len】

python 复制代码
str_demo2 = "12 imzhanzgszans 12"
nums = len(str_demo2)
print(nums)

2.7 字符串遍历【while】

python 复制代码
str_while = "sdlkhfsdkf"
index = 0
while index < len(str_demo2):
    print(str_demo2[index],end=',')
    index += 1

2.7 字符串遍历【for】

python 复制代码
for ele in str_demo2:
    print(ele,end=' ')

三、特点

  1. 只可以存储字符串
  2. 长度任意(取决于内存大小)
  3. 支持索引/下标
  4. 允许字符重复
  5. 不可修改
  6. 支持while/for循环

相关推荐
金銀銅鐵8 小时前
[Python] 基于欧几里得算法,实现分数约分计算器
python·数学
Lyn_Li10 小时前
Kaggle Top 5 | 198只股票、200条数据的金融预测——BattleFin高分方案从零复现
python·kaggle·比赛复盘·金融预测
小九九的爸爸15 小时前
前端想要入门Agent开发,要具备哪些Python基础?
python·agent·ai编程
阿耶同学16 小时前
手把手教你用 LangGraph 搭建三层嵌套 Agent 架构
python·程序员
花酒锄作田1 天前
Pydantic校验配置文件
python
hboot1 天前
AI工程师第四课 - 深度学习入门
pytorch·python·神经网络
ZhengEnCi2 天前
P2M-Matplotlib折线图完全指南-从数据可视化到趋势分析的Python绘图利器
python·matlab·数据可视化
ZhengEnCi2 天前
P2L-Matplotlib饼图完全指南-从数据可视化到图表定制的Python绘图利器
python·matlab
曲幽2 天前
你的REST接口还在“过度投喂”数据吗?——FastAPI + GraphQL实战避坑指南
python·fastapi·web·graphql·route·cors·rest·strawberry
用户8358086187912 天前
基于 Self-RAG 与列表级重排序的进阶 RAG 系统设计与实现
python