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循环

相关推荐
用户033212666367几秒前
使用 Python 将 HTML 内容添加到 PowerPoint 演示文稿中
python·html
看浪的路人2 分钟前
第4讲:MCP Client 开发——连接、发现、调用
windows·python·ai
snow@li8 分钟前
SpringBoot:AOP日志切面全景梳理/原理+流程+实战+避坑
java·开发语言·spring boot
Nil2089 分钟前
C++ emplace_back 与 push_back 详解
开发语言·c++
Swift社区10 分钟前
Python 开发环境怎么选?PyCharm、VS Code、Trae 谁更适合 AI 开发?
人工智能·python·pycharm
卷无止境13 分钟前
聊聊Web开发里的流式数据 从原理到FastAPI实战
后端·python·fastapi
SMF191914 分钟前
【PyCharm】让 PyCharm 使用 .venv 虚拟环境
ide·python·pycharm
修远客19 分钟前
感知模块:Agent的眼睛和耳朵 — 三层降级策略让Agent永不"失明"
python·agent
clear sky .32 分钟前
[freertos源码阅读]task.c任务篇
c语言·开发语言
circuitsosk41 分钟前
Prompt Engineering进阶:面向复杂业务场景的模板化管理与动态注入策略
python·langchain·prompt·跨境电商·rag·上下文管理·动态注入