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
复制代码
相关推荐
金銀銅鐵6 小时前
[Python] 从《千字文》中随机挑选汉字
后端·python
cup1111 小时前
[技术复盘] Windows Python 打包实战:Nuitka 环境踩坑总结与 CI 自动化构建全指南
python·ai·环境变量·ci·nuitka·skill
aqi0013 小时前
15天学会AI应用开发(七)有了大模型为什么还要引入RAG
人工智能·python·大模型·ai编程·ai应用
金銀銅鐵15 小时前
用 Python 实现 Take-Away 游戏
python·游戏
copyer_xyf15 小时前
Agent 流程编排
后端·python·agent
copyer_xyf16 小时前
Agent RAG
后端·python·agent
copyer_xyf16 小时前
【RAG】向量数据库:milvus
后端·python·agent
copyer_xyf16 小时前
Agent 记忆管理
后端·python·agent
星云穿梭1 天前
用Python写一个带图形界面的学生管理系统——完整教程
python