【问题标题】:How to remove \n at the end of each value?如何在每个值的末尾删除 \n?
【发布时间】:2019-11-21 13:50:49
【问题描述】:

我想进行输入,以便用户在每个新行上键入一个单独的数字。我设法把这段代码放在一起

def str2arr(str):
    arr = []
    for line in str:          
        arr.append(str.replace('\n', ''))
    return arr
import sys
a = sys.stdin.readlines()
print(a)

它几乎按照我的意愿工作,但输出看起来像

['6543\n', '6543\n', '7654\n']

有没有什么巧妙的方法可以去掉\n? 而且,我什至会用这种方法得到一个可用的整数吗?

提前谢谢你们。

【问题讨论】:

标签: python python-3.x list input


【解决方案1】:

你可以使用

a = ['6543\n', '6543\n', '7654\n']
integers = list(map(int, a))
print(integers)
# [6543, 6543, 7654]

【讨论】:

    【解决方案2】:

    看看string.strip。这应该会提供预期的结果。

    然后,您必须对列表中的每个条目调用 int()

    例子:

    >>> t = ['6543\n', '6543\n', '7654\n']
    >>> [int(x.strip()) for x in t]
    [6543, 6543, 7654]
    

    【讨论】:

    • int() 不介意尾随 \ns,所以 strip() 并不是真正需要的。
    • 有趣,不知道!
    • 显然尾随空格是可以的——绝对方便。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多