【问题标题】:Why is a `\n` appended to every value in the python dictionary? [duplicate]为什么python字典中的每个值都附加一个`\n`? [复制]
【发布时间】:2017-10-21 06:53:38
【问题描述】:

我的代码是:

quiz = {}
quiz["questions"]={}
templist = []

def checkint(i):
    try:
        int(i)
        return True
    except ValueError:
        return False


with open("sample",'r') as f:
    for x in f:
        x.rstrip()
        num,text = x.split(" ",1)
        print(text)
        num = num[:-1]
        if checkint(num):
            quiz["questions"][num] = {}
            quiz["questions"][num]["question"] = text
            templist.append(num)
        else:
            qn = templist.pop()
            quiz["questions"][qn][num] = text   
            templist.append(qn)

示例文件为:

1. Who is the sower in the parable of wheat and tares?

 a. Jesus

 b. Peter

 c. Angels

 d. Satan

当我打印字典测验时,输出在每个值的末尾都包含换行符 \n

{'问题': {'1': {'a': '耶稣\n', 'b': '彼得\n', 'c': 'Angels\n', 'd': 'Satan\n', 'question': '谁是播种者 小麦和稗子的比喻?\n'}, '2': {'question': '\n'}}}

为什么会这样?我应该怎么做才能摆脱\n

【问题讨论】:

  • 这与字典无关——如果您根本没有将它们写入字典,则从文件中读取的行仍然会有尾随换行符。请在未来尝试生成一个minimal reproducible example,其中删除了重新创建问题所必需的元素。
  • x = x.strip()

标签: python dictionary


【解决方案1】:

rstrip 返回删除了尾随字符的字符串副本。

改变这个:

x.rstrip()

收件人:

x = x.rstrip()

编辑:

您在num,text = x.split(" ",1) 中给出的第二个参数意味着:

如果给出了 maxsplit,则最多完成 maxsplit 拆分(因此,列表 最多有 maxsplit+1 个元素)。如果未指定 maxsplit 或 -1,则拆分次数没有限制(所有可能的 分裂)。

如果没有要拆分的内容,您将收到此错误。

你试过num,text = x.split(" ")吗?

或者至少一个拆分是强制性的?

【讨论】:

  • 我收到此错误:ValueError: not enough values to unpack (expected 2, got 1)
  • @OneFace ,您在哪一行收到此错误?
  • num,text = x.split(" ",1) - 这一行给出了错误
  • @OneFace,在我的回答中添加了解释。
  • 我想我明白了为什么会出现这个错误。最后一行只有一个元素。感谢您的回答
猜你喜欢
  • 2020-05-19
  • 2014-05-21
  • 2022-01-24
  • 2011-03-13
  • 1970-01-01
  • 2021-04-04
  • 2017-09-07
  • 1970-01-01
  • 2019-03-18
相关资源
最近更新 更多