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

如何用Python将数组中字符串按分隔符拆分为单词并格式化输出?

Python 按指定分隔符拆分数组字符串并格式化输出

核心实现思路

遍历数组中的每个字符串元素,用str.split(sep, maxsplit=1)方法按指定分隔符拆分出前两部分(即便字符串包含多个分隔符,也仅拆分一次),再按要求格式输出。

代码示例

tag_attribute = ['Content_ExportDate','Controller_SoftwareRevision','DataType_Owner']
separator = '_'  # 可替换为其他分隔符,比如'-'、'|'等

for item in tag_attribute:
    # 拆分字符串为两部分,maxsplit=1确保只拆分一次
    tag, attribute = item.split(separator, maxsplit=1)
    print(f"Tag: {tag}")
    print(f"Attribute: {attribute}")

关键细节说明

  • str.split(separator, maxsplit=1):separator是你指定的分隔符,maxsplit=1限制仅拆分一次,保证每个字符串被拆分为恰好两部分(前提是每个元素都包含该分隔符)。
  • 用f-string做格式化输出,写法简洁直观。

边界情况处理(可选)

如果数组里存在不含指定分隔符的元素,可加判断避免报错:

tag_attribute = ['Content_ExportDate','NoSeparatorItem','DataType_Owner']
separator = '_'

for item in tag_attribute:
    if separator in item:
        tag, attribute = item.split(separator, maxsplit=1)
        print(f"Tag: {tag}")
        print(f"Attribute: {attribute}")
    else:
        print(f"警告:元素 '{item}' 不含分隔符 '{separator}',跳过处理")

内容的提问来源于stack exchange,提问作者Quan Hoang Nguyen

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 22:01:02