Python中如何拆分多行字符串?使用split方法未成功的解决方案咨询
Hey there! Let's figure out how to split that multi-line string into your desired format in Python. I know you tried the standard split() method already without luck, so let's go through practical, targeted solutions based on common use cases:
1. Split by Line Breaks (Most Common Use Case)
If you just need to split the string into individual lines, use splitlines() instead of split('\n') — it handles all newline types (\n, \r\n, \r) automatically, which is way more reliable across different systems.
Example code:
multi_line_str = """Hello there This is a multi-line string Ready to be split!""" # Split into a list of lines split_lines = multi_line_str.splitlines() print(split_lines) # Output: ['Hello there', 'This is a multi-line string', 'Ready to be split!']
2. Split by a Custom Delimiter
If your string uses a specific separator (like ===, ||, or even a phrase) to divide sections, you can pass that separator directly to split(). Just remember to clean up extra whitespace or empty strings afterward if needed.
Example with a custom delimiter:
multi_line_str = """Section 1=== Section 2 that wraps across two lines=== Section 3""" # Split on the delimiter split_sections = multi_line_str.split('===') # Clean up: remove whitespace and empty entries clean_sections = [section.strip() for section in split_sections if section.strip()] print(clean_sections) # Output: ['Section 1', 'Section 2\nthat wraps across two lines', 'Section 3']
For more flexibility (like if the delimiter has random spaces around it), use regular expressions with re.split():
import re multi_line_str = """Section 1 === Section 2 that wraps across two lines=== Section 3""" # Split on any number of spaces + === + any number of spaces split_sections = re.split(r'\s*===\s*', multi_line_str) clean_sections = [s for s in split_sections if s] print(clean_sections)
3. Split into Fixed-Size Chunks
If you need to split the string into chunks of a specific format (like every 2 lines grouped together), use itertools.zip_longest to batch the lines:
from itertools import zip_longest multi_line_str = """Line 1 Line 2 Line 3 Line 4 Line 5""" lines = multi_line_str.splitlines() # Group every 2 lines into a tuple line_groups = list(zip_longest(*[iter(lines)]*2, fillvalue='')) print(line_groups) # Output: [('Line 1', 'Line 2'), ('Line 3', 'Line 4'), ('Line 5', '')]
If none of these fit your exact needs, share the exact input string and the format you want the output to be in — I can help tweak the solution to match perfectly!
内容的提问来源于stack exchange,提问作者anand

