Python实现列表与文本安全互转:解决分隔冲突问题
Safe List-Text Conversion Solution
To convert between lists and text without separator conflicts, we use a URL-inspired encoding scheme to escape special characters, then join/split with a delimiter that's safely escaped in list items.
Implementation Code
lis = ['abc', 'def', '123'] def encode_item(s): # Escape special characters in priority order s = s.replace('%', '%25') # Escape % first (it's the escape marker) s = s.replace('|', '%7C') # Escape the delimiter character s = s.replace('+', '%2B') # Escape + (used as space placeholder) s = s.replace(' ', '+') # Replace spaces with + return s def decode_item(s): # Reverse encoding steps to restore original content s = s.replace('+', ' ') # Restore spaces from + s = s.replace('%2B', '+') # Restore original + characters s = s.replace('%7C', '|') # Restore original delimiter characters s = s.replace('%25', '%') # Restore original % characters return s def list_to_text(lis): # Encode all items and join with delimiter encoded_items = [encode_item(item) for item in lis] return '|'.join(encoded_items) def text_to_list(text): # Split text into encoded items and decode each encoded_items = text.split('|') return [decode_item(item) for item in encoded_items]
Key Details
- Encoding Order: We escape characters in a specific sequence to prevent conflicts:
%is escaped first to avoid interfering with other escape sequences- The delimiter
|is converted to%7C(standard URL encoding for |) +is converted to%2Bsince+is used to represent spaces- Spaces are replaced with
+for compactness
- Decoding Order: Reverses the encoding steps to accurately restore original list items
- Delimiter Safety: Since all instances of
|in list items are escaped, splitting the text on|will never split an item incorrectly
Example Usage
# Test round-trip conversion test_list = ['cats dogs', 'cats+dogs', 'cats%2Bdogs', 'a|b+c% d'] converted_text = list_to_text(test_list) restored_list = text_to_list(converted_text) print("Original List:", test_list) print("Converted Text:", converted_text) print("Restored List:", restored_list) print("Conversion Match?", test_list == restored_list) # Outputs True
内容的提问来源于stack exchange,提问作者Kaan
相关产品推荐
相关产品推荐

