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

如何用Python将多行哈希值合并为以|分隔的单行

问题描述

我有若干哈希值,想要在Python中将它们全部合并为一行并用|分隔。尝试用join()方法时,它会拆分每个字符(比如第一行变成d|1|5|5等)。以下是输入示例及现有代码:

输入哈希值示例:

d155dd4712a53d94ddb7916da78e15762bb9ee55
11a50ecbd959d839323717811e0f687298448042
09a52c6b05159edd5edf5be58e16c58ed286c16e
0348395f05e7ec1db81a3bf1e65d0a3117f2ed1a
db578880bcc20ce89dc91e3ad445057af25f25e1
e7da2f446abd104a62f96213d45257dfb6536e9e
f6d8142f5bdfe6042fc5e0044a668d658592e0d2

现有代码:

import requests
import jq

url = 'http://192.168.1.224:8080/api/v2/torrents/info?filter=errored&category=test'

torrentListParsed = requests.get(url).json()

finalList = (jq.compile(".[] | .hash").input(torrentListParsed).text())

# 带引号:
# "d155dd4712a53d94ddb7916da78e15762bb9ee55"
# "11a50ecbd959d839323717811e0f687298448042"
# "09a52c6b05159edd5edf5be58e16c58ed286c16e"
# "0348395f05e7ec1db81a3bf1e65d0a3117f2ed1a"
# "db578880bcc20ce89dc91e3ad445057af25f25e1"
# "e7da2f446abd104a62f96213d45257dfb6536e9e"
# "f6d8142f5bdfe6042fc5e0044a668d658592e0d2"

finalListStripped = finalList.replace('"', '')
print(finalListStripped)

# 不带引号:
# d155dd4712a53d94ddb7916da78e15762bb9ee55
# 11a50ecbd959d839323717811e0f687298448042
# 09a52c6b05159edd5edf5be58e16c58ed286c16e
# 0348395f05e7ec1db81a3bf1e65d0a3117f2ed1a
# db578880bcc20ce89dc91e3ad445057af25f25e1
# e7da2f446abd104a62f96213d45257dfb6536e9e
# f6d8142f5bdfe6042fc5e0044a668d658592e0d2
解决方法

问题核心是jq的.text()方法返回的是单个换行分隔的字符串,而非字符串列表。直接对这个字符串调用join()会遍历每个字符,导致拆分单个哈希值的问题。以下两种方式可以解决:

方式一:直接从JSON提取哈希列表(无需jq)

跳过jq,直接遍历解析后的JSON数据提取哈希值,得到真正的字符串列表后再合并:

import requests

url = 'http://192.168.1.224:8080/api/v2/torrents/info?filter=errored&category=test'

torrentListParsed = requests.get(url).json()
# 提取所有哈希值到列表
hash_list = [torrent['hash'] for torrent in torrentListParsed]
# 用|分隔合并成一行
result = '|'.join(hash_list)
print(result)

方式二:处理jq返回的字符串

如果必须使用jq,将返回的字符串按换行符分割为列表,过滤空元素后再合并:

import requests
import jq

url = 'http://192.168.1.224:8080/api/v2/torrents/info?filter=errored&category=test'

torrentListParsed = requests.get(url).json()
finalList = jq.compile(".[] | .hash").input(torrentListParsed).text()
# 按换行分割,去除引号和空行
hash_list = [h.strip('"') for h in finalList.split('\n') if h]
# 合并为一行
result = '|'.join(hash_list)
print(result)

两种方式最终输出结果示例:

d155dd4712a53d94ddb7916da78e15762bb9ee55|11a50ecbd959d839323717811e0f687298448042|09a52c6b05159edd5edf5be58e16c58ed286c16e|0348395f05e7ec1db81a3bf1e65d0a3117f2ed1a|db578880bcc20ce89dc91e3ad445057af25f25e1|e7da2f446abd104a62f96213d45257dfb6536e9e|f6d8142f5bdfe6042fc5e0044a668d658592e0d2

内容的提问来源于stack exchange,提问作者Spykerwolf

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 12:50:16