Python---字符串

字符串特点

  1. 只可以存储字符串

  2. 长度任意 (取决于内存大小)

  3. 支持下标索引

  4. 允许重复字符串存在

  5. 不可以修改 (增加或删除元素等)

  6. 支持for和while循环

字符串的下标索引

python 复制代码
# 字符串的下标索引
从前向后,下标从0开始
从后向前,下标从-1开始
语法:字符串[下标]

例子:

python 复制代码
my_str = "hello world"

# 取第一个
value1 = my_str[0]
print(value1)

# 取最后一个
value2 = my_str[-1]
print(value2)


my_str[2] = "2"  # 不能修改 

查找特定字符串的下表索引值---index

python 复制代码
# 查找特定字符串的下表索引值---index()
语法: 字符串.index(字符串)

print(my_str.index("h"))

字符串替换

python 复制代码
# 字符串的替换
语法: 字符串.replace(字符串1, 字符串2)   ----------- 字符串1替换为字符串2
注意:不是修改字符串本身,而是得到一个新的字符串

例子:

python 复制代码
my_str = "hello world"
new_str = my_str.replace('hello','hello1')
print(my_str)    # hello world
print(new_str)   # hello1 world

字符串的分割

python 复制代码
# 字符串的分割
语法: 字符串.split(分隔符字符串)
功能: 按照指定的分隔符字符串,将字符串划分为多个字符串,并存入列表对象中
注意:字符串本身不变,而是得到了一个列表对象

例子:

python 复制代码
my_str1 = "hello python hello world"
new_str1 = my_str1.split(" ")
print(new_str1)  # ['hello', 'python', 'hello', 'world']
print(my_str1)  # hello python hello world

字符串的规整操作

python 复制代码
# 字符串的规整操作(去前后空格)
语法:字符串.strip()

# 字符串的规整操作(去前后指定字符串)
语法:字符串.strip(字符串)

例子:

python 复制代码
my_str2 = "       hello python hello world         "
print(my_str2)
print(my_str2.strip())

my_str3 = "12hello python hello world21"
print(my_str3.strip("12"))

统计某字符串的出现次数 --- count

python 复制代码
my_str4 = "121232564862"
count = my_str4.count('2')
print(count)  # 4

统计字符串长度 --- len

python 复制代码
my_str5 = "121232564862"
num = len(my_str5)
print(num)  # 12
相关推荐
番石榴AI36 分钟前
java版的ocr推荐引擎——JiaJiaOCR 2.0重磅升级!纯Java CPU推理,新增手写OCR与表格识别
java·python·ocr
时光轻浅,半夏挽歌1 小时前
python不同格式文件的读写方式(json等)
python·json
测试人社区-千羽1 小时前
边缘计算场景下的智能测试挑战
人工智能·python·安全·开源·智能合约·边缘计算·分布式账本
抽象带篮子1 小时前
Pytorch Lightning 框架运行顺序
人工智能·pytorch·python
哇哈哈&2 小时前
安装wxWidgets3.2.0(编译高版本erlang的时候用,不如用rpm包),而且还需要高版本的gcc++19以上,已基本舍弃
linux·数据库·python
luod2 小时前
pymysql执行DDL语句
python
song5013 小时前
鸿蒙 Flutter 图像识别进阶:物体分类与花卉识别(含离线模型)
人工智能·分布式·python·flutter·3d·华为·分类
Mqh1807623 小时前
day 35 文件的拆分和使用
python
虚假程序设计3 小时前
pythonnet 调用C接口
c语言·python
dhdjjsjs3 小时前
Day32 PythonStudy
python