Python入门——字符串

Python快速入门(1)------字符串

最近需要使用到python,本系列适合有其他编程语言(C/C++/Java)基础的同学,帮助大家一起快速上手Python,主要介绍Python编程常用操作与其他语言的区别。本节主要介绍python的字符串

字符串

Python字符串常用操作
索引/下标访问
常用方法
常用
倒序访问
截取/切片
长度
判空
大小写
删除空白
分割
title()
upper()
lower()
strip()
lstrip()
rstrip()
spilt()
partition()

索引访问
常用

与其他语言一样,python的字符串支持下表访问

python 复制代码
message = "flower,flow,flight"
# 访问第一个字符
message[0]

除此之外,python字符串下标访问还支持倒序访问 、截取

倒序访问

python支持倒序访问,message[-n]即倒数第n个字符,但是无论正序还是倒序都会有越界访问检查,越界时出现IndexError

python 复制代码
message = "flower,flow,flight"
# 访问倒数第1个字符t
message[-1]
# 越界IndexError: string index out of range
message[-100]
截取/切片

其他语言截取字符串一般需要通过方法substring(),python直接根据索引可以切片,且与大多数编程语言一样是左闭右开 。python支持倒序访问截取,且遵循startIndex < endIndex,否则直接返回空字符串。

切片的完整语法:[起始索引:结束索引:步长],步长默认是 1(正向,如果为负则为负向),起始索引与结束索引可选,默认为0和字符串长度-1。

步长为 0(无效,直接报错),索引不会报错自动终止

python 复制代码
message = "flower,flow,flight"
# 截取flower
message[0:6]
# 倒序访问截取flight
message[-7:-1]
# 空字符串
message[-1:-7]

这里有一些常用的技巧

  • 步长n,取所有字符(每隔n-1个取1个) :s[::n]
  • 取偶数索引子字符串 :s[::2]
  • 取奇数索引子字符串 :s[1::2]
  • 反转字符串 :s[::-1]
常用方法
长度
python 复制代码
print(len(message))
判空
python 复制代码
empty_str = ""
# 方法一 if not
if not empty_str:
    print("空字符串")
# 方法二 == ""
print(empty_str == "")
# 方法三 判断长度
print(len(empty_str) == 0)
# 如果有空格
print(" ".isspace())
大小写
python 复制代码
message = "flower,flow,flight"
# 所有单词
print(message.title())
# 全大写
print(message.upper())
# 全小写
print(message.lower())
删除空白

python的strip()仅能删除ASCII码下的半角空格,这个是与JDK11中strip()的区别,相当于trim()

python 复制代码
# 输出:message
print(" message ".strip())
# 输出:message[空格]
print(" message ".lstrip())
# 输出:[空格]message
print(" message ".rstrip())
# 输出:essage[空格]
print(" message ".rstrip(" m"))
分割
  • split():按分割符分割为多个部分,返回列表

  • partition():按分割符分割为2部分,并保留分割符,返回元组

python 复制代码
message = "flower,flow,flight"
# 输出 ['flower', 'flow', 'flight']
print(message.split(","))
# 输出 ('flower', ',', 'flow,flight')
print(message.partition(","))
相关推荐
落羽的落羽1 小时前
【C++】现代容器: tuple、optional、variant、any、string_view
linux·开发语言·数据结构·c++·人工智能·计算机网络·算法
木子欢儿1 小时前
Ubuntu 26.04 LTS 安装Python 3.12
linux·运维·服务器·python·ubuntu
Wellijohn1 小时前
Python 异步并发:我把 5 个坑踩完了,你照着抄模板就行
python
AI创界者2 小时前
Python 进阶实战(六十二章):分布式定时任务、异步工作流与幂等补偿机制实战
人工智能·python·aigc
小飞在努力3 小时前
【实现负载均匀在线判题④】接入 cpp-httplib 实现编译服务 HTTP 网络化
c语言·开发语言·c++·笔记·http
炸薯条!3 小时前
Python面向对象基础:类与对象、实例方法、魔法方法和属性详解
java·开发语言·python
CappuccinoRose3 小时前
前端开发交互体系 - 汇总篇
开发语言·前端·javascript·css·html·交互
tryCbest4 小时前
Python 爬虫从入门到实战(二):进阶篇——反爬对抗、并发与动态页面
开发语言·爬虫·python
VIP_CQCRE4 小时前
GPT Image 2.6 动态表情交付别只发预览:GIF 文件校验、哈希清单与下载排错
图像处理·人工智能·python·gif
2601_967987374 小时前
使用 NumPy 和 Python 实现梯度下降
python·机器学习·线性回归·numpy·梯度下降