首页/发现新知
视界 · 深度阅读

Python中字符串分割split与拼接join的常用方法整理

分割和拼接在处理结构化文本时无处不在,本文将系统讲解Python中字符串分割与拼接的核心方法,涵盖基本用法、maxsplit限制、特殊行为、性能对比及多分隔符处理,希望对大家有所帮助

目录
  • 一、开篇:拆开和拼起来都很有用
  • 二、split():把字符串拆成列表
    • 2.1 基本用法
    • 2.2 限制分割次数(maxsplit)
    • 2.3 split() 的特殊行为
    • 2.4 splitlines():按行分割
  • 三、partition() 和 rpartition():一刀切三段
    • 3.1 基本用法
    • 3.2 partition() 比 split() 优雅的场景
  • 四、join():把列表拼成字符串
    • 4.1 基本用法
    • 4.2 join() 的多种应用
    • 4.3 join() 的性能优势
  • 五、split() 和 join() 的组合应用
    • 5.1 文本格式转换
    • 5.2 数据清理和标准化
    • 5.3 矩阵/表格的转置
  • 六、切割高级操作
    • 6.1 多分隔符分割
    • 6.2 保留分隔符的分割
  • 七、实战:CSV解析器
    • 八、性能对比与最佳实践
      • 九、本篇小结

        一、开篇:拆开和拼起来都很有用

        上一篇我们学了字符串的查找与替换。今天要讲的两个操作——分割(split)和拼接(join)——互为逆操作。一个把字符串按规则拆成列表,一个把列表按规则合回字符串。

        分割和拼接在处理结构化文本时无处不在:解析CSV文件的一行数据、拆分URL路径、拼接SQL查询语句、格式化日志输出——几乎每个和文本打交道的程序都会用到它们。

        二、split():把字符串拆成列表

        2.1 基本用法

        # 按空格分割(默认行为)
        text = 'Python Java Go Rust'
        result = text.split()
        print(result)  # ['Python', 'Java', 'Go', 'Rust']
        
        # 按指定分隔符分割
        csv_line = '小明,25,北京,工程师'
        fields = csv_line.split(',')
        print(fields)  # ['小明', '25', '北京', '工程师']
        
        # 按换行符分割多行文本
        multiline = '第一行\n第二行\n第三行'
        lines = multiline.split('\n')
        print(lines)  # ['第一行', '第二行', '第三行']
        

        2.2 限制分割次数(maxsplit)

        text = 'a-b-c-d-e'
        
        # 不限制
        print(text.split('-'))       # ['a', 'b', 'c', 'd', 'e']
        
        # 只分割1次
        print(text.split('-', 1))    # ['a', 'b-c-d-e']
        
        # 分割2次
        print(text.split('-', 2))    # ['a', 'b', 'c-d-e']
        
        # 从右边开始分割
        print(text.rsplit('-', 2))   # ['a-b-c', 'd', 'e']
        

        maxsplit的实用场景:解析"键值对"类数据时,只分割第一个分隔符:

        # 解析HTTP头
        header = 'Content-Type: application/json; charset=utf-8'
        key, value = header.split(':', 1)
        print(f'键: {key.strip()}')    # 键: Content-Type
        print(f'值: {value.strip()}')  # 值: application/json; charset=utf-8
        
        # 解析命令行参数
        command = 'user create --name 小明 --role admin'
        cmd, *args = command.split()
        # 或者更复杂的情况用partition
        

        2.3 split() 的特殊行为

        # 默认split()和split(' ')的行为不同!
        text = 'a   b  c    d'
        
        # split()(无参数):将连续的空白符视为一个分隔符,自动去除首尾空白
        print(text.split())        # ['a', 'b', 'c', 'd']
        
        # split(' ')(有参数):严格按照每个空格分割
        print(text.split(' '))     # ['a', '', '', 'b', '', 'c', '', '', '', 'd']
        
        # 字符串首尾有分隔符时
        text = ',a,b,c,'
        print(text.split(','))     # ['', 'a', 'b', 'c', ''](首尾有空字符串)
        print([x for x in text.split(',') if x])  # ['a', 'b', 'c'](过滤空串)
        

        一个常见的坑:split() vs split(' '):

        • 'hello world'.split() → ['hello', 'world'](连续空格被合并)
        • 'hello world'.split(' ') → ['hello', '', 'world'](中间有空字符串)

        2.4 splitlines():按行分割

        text = '第一行\n第二行\r\n第三行\n第四行'
        
        # splitlines()自动处理各种换行符
        lines = text.splitlines()
        print(lines)  # ['第一行', '第二行', '第三行', '第四行']
        
        # splitlines(keepends=True):保留换行符
        lines_with_ends = text.splitlines(keepends=True)
        print(lines_with_ends)  # ['第一行\n', '第二行\r\n', '第三行\n', '第四行']
        
        # 和split('\n')的对比
        # split('\n')不处理\r\n,可能留下\r
        

        三、partition() 和 rpartition():一刀切三段

        3.1 基本用法

        partition() 在第一次出现分隔符的位置把字符串切成三部分:(分隔符之前, 分隔符本身, 分隔符之后)。找不到分隔符时返回 (原字符串, ‘’, ‘’)。

        # partition:分割为三部分
        text = 'Python@Java@Go'
        print(text.partition('@'))   # ('Python', '@', 'Java@Go')
        
        # rpartition:从右边开始找分隔符
        print(text.rpartition('@'))  # ('Python@Java', '@', 'Go')
        
        # 找不到分隔符时
        print(text.partition('#'))   # ('Python@Java@Go', '', '')
        

        3.2 partition() 比 split() 优雅的场景

        # 场景一:解析URL的协议部分
        url = 'https://www.example.com/path?query=value'
        protocol, _, rest = url.partition('://')
        print(protocol)  # https
        print(rest)      # www.example.com/path?query=value
        
        # 场景二:解析邮箱地址
        email = 'user@example.com'
        local_part, _, domain = email.partition('@')
        print(f'用户名: {local_part}')  # 用户名: user
        print(f'域名: {domain}')        # 域名: example.com
        
        # 场景三:解析MySQL连接字符串
        conn_str = 'mysql://user:password@localhost:3306/dbname'
        # 切出协议
        protocol, _, rest = conn_str.partition('://')
        # 切出认证和服务器
        auth, _, server_db = rest.rpartition('@')
        user, _, password = auth.partition(':')
        server, _, dbname = server_db.partition('/')
        print(f'用户: {user}, 密码: {password}, 服务器: {server}, 数据库: {dbname}')
        

        何时用 partition() 而不是 split()?

        • 当你确定只需要切一次,并且可能需要保留分隔符时:用 partition()
        • 当你需要切多次或不确定次数时:用 split()

        四、join():把列表拼成字符串

        4.1 基本用法

        join() 的作用和 split() 相反——它把一个可迭代对象中的字符串拼接起来,中间插入分隔符。

        # 基本拼接
        words = ['Python', 'Java', 'Go', 'Rust']
        result = ', '.join(words)
        print(result)  # Python, Java, Go, Rust
        
        # 无分隔符拼接
        print(''.join(['a', 'b', 'c']))  # abc
        
        # 用换行符拼接
        lines = ['第一行', '第二行', '第三行']
        print('\n'.join(lines))
        
        # 用制表符拼接(生成TSV格式)
        print('\t'.join(['姓名', '年龄', '城市']))
        

        join() 要求所有元素都是字符串。如果有非字符串元素,会报 TypeError:

        items = ['项目', 1, '测试', 2]
        # '-'.join(items)  # TypeError!
        
        # 需要先转换
        result = '-'.join(str(item) for item in items)
        print(result)  # 项目-1-测试-2
        

        4.2 join() 的多种应用

        # 构建SQL查询
        columns = ['name', 'age', 'city']
        placeholders = ', '.join(['%s'] * len(columns))
        query = f'INSERT INTO users ({", ".join(columns)}) VALUES ({placeholders})'
        print(query)
        # INSERT INTO users (name, age, city) VALUES (%s, %s, %s)
        
        
        # 生成HTML
        items = ['苹果', '香蕉', '橘子']
        html_list = '
          \n' + '\n'.join(f'
        • {item}
        • ' for item in items) + '\n
        ' print(html_list) # 生成文件路径 path_parts = ['home', 'user', 'documents', 'report.pdf'] path = '/'.join(path_parts) print(path) # home/user/documents/report.pdf # 格式化输出表格 data = [ ['小明', '25', '北京'], ['小红', '23', '上海'], ['小刚', '26', '广州'], ] # 每行的列用 | 分隔 for row in data: print('| ' + ' | '.join(row) + ' |')

        4.3 join() 的性能优势

        在循环中用 + 拼接字符串性能很差,而 join() 只需分配一次内存:

        import time
        
        words = ['hello'] * 100000  # 10万个字符串
        
        # 方法一:用 +(慢)
        start = time.perf_counter()
        result = ''
        for word in words:
            result += word
        elapsed_plus = time.perf_counter() - start
        print(f'用 + 拼接:{elapsed_plus:.4f}秒')
        
        # 方法二:用 join(快)
        start = time.perf_counter()
        result = ''.join(words)
        elapsed_join = time.perf_counter() - start
        print(f'用 join:{elapsed_join:.4f}秒')
        
        # 时间差距可能是几十倍甚至上百倍!
        

        五、split() 和 join() 的组合应用

        5.1 文本格式转换

        # CSV格式 → 固定宽度文本 → SQL INSERT
        csv_data = '小明,25,北京,工程师'
        
        # 拆开
        name, age, city, job = csv_data.split(',')
        
        # 重新组合
        sql = f"INSERT INTO users (name, age, city, job) VALUES ('{name}', {age}, '{city}', '{job}')"
        print(sql)
        
        
        # 日期格式转换:2024/05/30 → 2024-05-30
        date_slash = '2024/05/30'
        date_dash = '-'.join(date_slash.split('/'))
        print(date_dash)  # 2024-05-30
        
        
        # 倒转单词顺序
        sentence = 'I love Python programming'
        words = sentence.split()
        reversed_sentence = ' '.join(reversed(words))
        print(reversed_sentence)  # programming Python love I
        

        5.2 数据清理和标准化

        # 清理多余的空白
        def normalize_whitespace(text):
            """将连续的空白字符统一为单个空格"""
            return ' '.join(text.split())
        
        text = 'Hello    world\t\tPython   \n\n   编程'
        print(normalize_whitespace(text))  # Hello world Python 编程
        
        
        # URL slug生成
        def slugify(text):
            """将标题转为URL友好的slug格式"""
            # 转小写,替换空格为连字符,过滤非字母数字的字符
            slug = '-'.join(text.lower().split())
            # 更复杂的实现可以用正则,但基本思路仍然是split+join
            return slug
        
        print(slugify('My First Blog Post'))  # my-first-blog-post
        

        5.3 矩阵/表格的转置

        # 用split和join实现文本表格的行列转置
        table = [
            '姓名,年龄,城市',
            '小明,25,北京',
            '小红,23,上海',
            '小刚,26,广州',
        ]
        
        # 每行按逗号分割
        rows = [row.split(',') for row in table]
        
        # 转置(行列互换)
        transposed = list(zip(*rows))
        
        # 每列按逗号拼接回去
        result = [','.join(col) for col in transposed]
        for line in result:
            print(line)
        
        # 输出:
        # 姓名,小明,小红,小刚
        # 年龄,25,23,26
        # 城市,北京,上海,广州
        

        六、切割高级操作

        6.1 多分隔符分割

        Python的 split() 只支持单个分隔符。如果需要多个分隔符,有几种解决方案:

        import re
        
        text = '苹果,香蕉;橘子|葡萄 西瓜'
        
        # 方案一:多次replace + split
        result = text.replace(';', ',').replace('|', ',').replace(' ', ',').split(',')
        print(result)  # ['苹果', '香蕉', '橘子', '葡萄', '西瓜']
        
        # 方案二:用正则表达式(更灵活)
        result = re.split(r'[,;| ]', text)
        print(result)  # ['苹果', '香蕉', '橘子', '葡萄', '西瓜']
        
        # 方案三:re.split保留分隔符
        result = re.split(r'([,;| ])', text)
        print(result)  # ['苹果', ',', '香蕉', ';', '橘子', '|', '葡萄', ' ', '西瓜']
        

        6.2 保留分隔符的分割

        import re
        
        # 用re.split的分组捕获来保留分隔符
        text = 'Hello, World! How are you?'
        result = re.split(r'([,.!? ])', text)
        # 过滤空字符串
        result = [s for s in result if s and s != ' ']
        print(result)  # ['Hello', ',', 'World', '!', 'How', 'are', 'you', '?']
        
        
        # 用在文本分句
        def split_sentences(text):
            """按句末标点分割句子,保留标点符号"""
            import re
            parts = re.split(r'([。!?.!?])', text)
            sentences = []
            for i in range(0, len(parts) - 1, 2):
                sentences.append(parts[i] + parts[i + 1])
            if len(parts) % 2 == 1 and parts[-1]:
                sentences.append(parts[-1])
            return sentences
        
        text = '你好!今天天气不错。你吃饭了吗?'
        print(split_sentences(text))
        # ['你好!', '今天天气不错。', '你吃饭了吗?']
        

        七、实战:CSV解析器

        def parse_csv_line(line, delimiter=',', quote_char='"'):
            """
            解析CSV的一行(支持引号内的分隔符)
            例如: 小明,"北京,朝阳区",25 → ['小明', '北京,朝阳区', '25']
            """
            fields = []
            current_field = ''
            in_quotes = False
        
            for char in line:
                if char == quote_char:
                    in_quotes = not in_quotes
                elif char == delimiter and not in_quotes:
                    fields.append(current_field)
                    current_field = ''
                else:
                    current_field += char
        
            fields.append(current_field)
            return fields
        
        
        # 测试
        csv_line = '小明,"北京,朝阳区",25,工程师'
        fields = parse_csv_line(csv_line)
        print(fields)  # ['小明', '北京,朝阳区', '25', '工程师']
        
        # 标准CSV处理还是用csv模块
        import csv
        line = '小明,"北京,朝阳区",25,工程师'
        reader = csv.reader([line])
        print(next(reader))  # ['小明', '北京,朝阳区', '25', '工程师']
        

        八、性能对比与最佳实践

        # split vs partition(只需要切一次时)
        text = 'key: value with many colons: extra data'
        
        # split(会扫描整个字符串)
        key, value = text.split(':', 1)  # 用了maxsplit=1还行
        
        # partition(找到第一个就停止,更高效)
        key, _, value = text.partition(':')
        
        # 拼接:join vs +=
        # 1. 少量拼接(<5个):+ 或 f-string 更简洁
        name = '小明'
        greeting = '你好,' + name + '!'
        # 或
        greeting = f'你好,{name}!'
        
        # 2. 列表拼接:join
        words = ['Python', 'Java', 'Go', 'Rust']
        result = ', '.join(words)
        
        # 3. 循环拼接:列表收集 + join
        lines = []
        for i in range(1000):
            lines.append(f'第{i}行')
        result = '\n'.join(lines)
        

        九、本篇小结

        分割与拼接的核心方法:

        方法 方向 说明
        split() 字符串→列表 按分隔符分割
        rsplit() 字符串→列表 从右边开始分割
        splitlines() 字符串→列表 按换行符分割
        partition() 字符串→三元组 一刀切三段
        rpartition() 字符串→三元组 从右边一刀切
        join() 列表→字符串 用分隔符拼接

        核心技巧:

        • 需要切多次用 split(),只需切一次用 partition()
        • 大量字符串拼接用 join(),少量用 + 或 f-string
        • split() 和 join() 互为逆操作,经常搭配使用
        • 多分隔符分割用正则 re.split()

        以上就是Python中字符串分割split与拼接join的常用方法整理的详细内容,更多关于Python字符串分割与拼接的资料请关注爱读视界其它相关文章!

        您可能感兴趣的文章:

        • Python字符串常用方法之分割与拼接教学
        • Python基础指南之字符串分割与拼接的常用方法详解
        • python分割和拼接字符串
        • Python字符串操作strip()和split()方法详解
        • python多个字符串条件分割split方式
        • python如何使用split多字符分割字符串的方法
        • python字符串拼接+和join的区别详解
        读到这里,发现更多一点。探索更多内容 ↗