在python中将多行字符串拆分为一种格式?
我正在尝试将多行字符串拆分为一种格式 我尝试了这个链接中的解决方案,但没有成功在python中将多行字符串拆分为一种格式?,python,python-3.x,string,split,Python,Python 3.x,String,Split,我正在尝试将多行字符串拆分为一种格式 我尝试了这个链接中的解决方案,但没有成功 lines = [line for line in txt.splitlines() if line] for idx in range(0, len(lines), 2): keys = lines[idx].split() values = lines[idx+1].split() for k, v in zip(keys, values): print(f"{k}:{v}&qu
lines = [line for line in txt.splitlines() if line]
for idx in range(0, len(lines), 2):
keys = lines[idx].split()
values = lines[idx+1].split()
for k, v in zip(keys, values):
print(f"{k}:{v}")
输出:
1.name:chandu
2.address:madhuranagr
3.option:234
4a.option1:345
4b.option2:456
4c.option3:789
下面是一个可能的解决方案:
# Gets an array where each entry is a line.
lines = txt.split('\n')
# Discard first and last lines, which are empty.
lines = lines[1:-1]
# Iterate over pairs of lines.
for i in range(len(lines)//2):
# Compute indices for the relevant lines
question_index = 2*i
answer_index = 2*i + 1
# Split the entries in a line, using strip() to remove the last (empty) entry.
question_parts = lines[question_index].strip().split(' ')
answer_parts = lines[answer_index].strip().split(' ')
# Print question-answer pairs.
for j in range(len(question_parts)):
# Skip questions without answers.
if j < len(answer_parts):
print('%s:%s' % (question_parts[j], answer_parts[j]))
#获取一个数组,其中每个条目都是一行。
lines=txt.split('\n')
#丢弃第一行和最后一行,它们是空的。
行=行[1:-1]
#在成对的行上迭代。
对于范围内的i(len(行)//2):
#计算相关行的索引
问题指数=2*i
答案指数=2*i+1
#在一行中拆分条目,使用strip()删除最后一个(空)条目。
问题部分=行[问题索引].strip().split(“”)
答案部分=行[答案索引].strip().split(“”)
#打印问答对。
对于范围内的j(len(问题_部分)):
#跳过没有答案的问题。
如果j
它解决了这个特定的例子,但它不处理所有的边缘情况:例如,是否有可能中间的一个答案丢失了?如果是这样,那么这种情况下的数据结构是怎样的?我认为您需要更好地指定输入格式。例如,如果不是“345456789”行,而是只有“456”,会发生什么?我怎么知道答案指的是什么问题?答案是4a.option1、4b.option2、4c.option3还是4d.option4是不明确的,即使在前面和后面加上空格,比如“456”。