You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 %2B since + 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 19:56:13