Python——字符串常用操作

字符串常用操作

  • [一、字符串最常用 18 个操作](#一、字符串最常用 18 个操作)
    • [1. 字符串定义](#1. 字符串定义)
    • [2. 字符串拼接](#2. 字符串拼接)
    • [3. 获取长度](#3. 获取长度)
    • [4. 索引、切片(高频)](#4. 索引、切片(高频))
    • [5. 去空格(超级常用)](#5. 去空格(超级常用))
    • [6. 大小写转换](#6. 大小写转换)
    • [7. 判断开头/结尾](#7. 判断开头/结尾)
    • [8. 查找字符位置](#8. 查找字符位置)
    • [9. 替换字符串](#9. 替换字符串)
    • [10. 分割字符串(接口测试高频)](#10. 分割字符串(接口测试高频))
    • [11. 列表拼接成字符串](#11. 列表拼接成字符串)
    • [12. 判断字符串内容](#12. 判断字符串内容)
    • [13. 包含判断(断言必用)](#13. 包含判断(断言必用))
    • [14. 统计子串出现次数](#14. 统计子串出现次数)
    • [15. 居中、填充](#15. 居中、填充)
    • [16. 转义字符](#16. 转义字符)
    • [17. 字符串转 列表/元组/集合](#17. 字符串转 列表/元组/集合)
    • [18. 格式化(最常用)](#18. 格式化(最常用))
  • 面试常问

一、字符串最常用 18 个操作


1. 字符串定义

python 复制代码
s = "hello"
s = 'hello'
s = """hello"""  # 多行

2. 字符串拼接

python 复制代码
a = "hello" + " " + "world"
a = f"hello {name}"   # 推荐
a = "hello %s" % name
a = "hello {}".format(name)

3. 获取长度

python 复制代码
len(s)

4. 索引、切片(高频)

python 复制代码
s[0]      # 第一个字符
s[-1]     # 最后一个
s[1:3]    # 切片
s[::-1]   # 反转字符串(面试必问)

5. 去空格(超级常用)

python 复制代码
s.strip()   # 去左右空格、换行
s.lstrip()  # 去左边
s.rstrip()  # 去右边

6. 大小写转换

python 复制代码
s.upper()   # 转大写
s.lower()   # 转小写
s.capitalize()  # 首字母大写
s.title()   # 每个单词首字母大写

7. 判断开头/结尾

python 复制代码
s.startswith("http")  # 是否以xx开头
s.endswith(".jpg")    # 是否以xx结尾

8. 查找字符位置

python 复制代码
s.find("ll")    # 返回索引,找不到返回-1
s.index("ll")   # 找不到报错

9. 替换字符串

python 复制代码
s.replace("old", "new")
s.replace("a", "b", 1)  # 只替换1次

10. 分割字符串(接口测试高频)

python 复制代码
s.split(",")   # 按逗号切,返回列表
s.split()      # 按空格/换行切

11. 列表拼接成字符串

python 复制代码
",".join(["a","b","c"])  # "a,b,c"

12. 判断字符串内容

python 复制代码
s.isdigit()    # 是否全是数字(0-9)
s.isalpha()    # 是否全是字母(a-z A-Z)
s.isalnum()    # 是否字母+数字(无符号、无空格)
s.islower()		# 是否全是小写字母
s.isupper()		# 是否全是大写字母
s.isspace()		# 是否全是空白字符(空格、制表、换行)

13. 包含判断(断言必用)

python 复制代码
if "token" in s:
if "error" not in s:

14. 统计子串出现次数

python 复制代码
s.count("l")

15. 居中、填充

python 复制代码
s.center(20, "*")
s.ljust(20)
s.rjust(20)

16. 转义字符

python 复制代码
\n  换行
\t  制表符
\"  双引号
\\  反斜杠

17. 字符串转 列表/元组/集合

python 复制代码
list(s)
tuple(s)
set(s)

18. 格式化(最常用)

python 复制代码
name = "tom"
age = 18
s = f"我是{name},年龄{age}"

面试常问

判断字符串是不是手机号

python 复制代码
# 用 isdigit() + 长度判断
def is_phone(s):
    return s.isdigit() and len(s) == 11

判断字符串时不是有效6位数字验证码

python 复制代码
# 用 isdigit() + 长度判断
def is_code(s):
    return s.isdigit() and len(s) == 6

判断字符串是不是合法邮箱?

python 复制代码
# 简单方式
# 包含@但不在开头,包含.但不在结尾
def is_email(s):
    return "@" in s and not s.startswith("@") and "." in s and not s.endswith(".")


print(is_email("@qqcom."))  # False
print(is_email("@qq.com"))  # False
print(is_email("qq@com."))  # False
print(is_email("12@qq.com"))  # True

# ------------------------------------------------
# 实际工作中使用正则表达式来进行校验

```python
import re


def is_valid_email(email):
    # 标准邮箱正则(通用、够用、面试必背)
    pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
    return re.match(pattern, email) is not None


print(is_valid_email("test@163.com"))  # True
print(is_valid_email("test.com"))  # False
print(is_valid_email("test@.com"))  # False
复制代码
相关推荐
xurileidian4 小时前
第 24 篇 · 边玩边学Python · while 与死循环怎么退
服务器·前端·python
默 语4 小时前
HarmonyOS7 事件分发控制(二):onTouchIntercept 镂空玻璃卡——圆内自己接,圆外放行
android·java·开发语言
有个傻瓜4 小时前
工具调用参数每次都差一截:finish_reason=length 输出预算截断的排错复盘与四种分诊实测
python·故障排查·ai agent·大模型应用开发·function calling
zhanghongyi_cpp5 小时前
第5章 学习自测
python·学习
Amumu121385 小时前
TypeScript学习: 基础知识(二)
开发语言·typescript·ecmascript
sharemylove6 小时前
Java 异常与常用类 学习笔记
java·开发语言·经验分享·笔记·学习
小灰灰搞电子6 小时前
C 语言基础:动态内存管理详解
c语言·开发语言
打工仔折腾 AI6 小时前
L3 静态源码取证|工程评测:python-oracledb 驱动评估中的样本偏差陷阱
开发语言·人工智能·后端·python·性能优化
IvanCodes7 小时前
LangChain(15):LangSmith 应用评估与回归测试
python·langchain·agent
Amumu121387 小时前
TypeScript学习: 进阶知识
开发语言·学习·typescript