sys.stdin.read() 如何更改文字参数的结构?

发布于 2025-01-14 22:25:43 字数 1196 浏览 4 评论 0原文

背景故事:在我之前的文章中,我想知道某个函数是否可以有效地替换另一个函数,而且确实如此,所以,从技术上讲,我不需要答案来帮助我的项目,但我是只是想知道“如果我继续使用 sys.stdin.read() 而不是 input(),我将如何克服我的障碍之一?”

我的问题: 对于某些人原因,当我使用 sys.stdin.read() 时它不适用于文字字符串或字符。这是我的代码的一个懒惰但有效的重建...

print("Type p or P for a pyramid")
print("Type s or S for the sum and product of two numbers")
choice_1 = sys.stdin.read()

# edge case for inputted char being invalid
if str(choice_1) != ('p' or 'P' or 's' or 'S')
    err_test = 'z'
    while str(err_test) != ('p' or 'P' or 's' or 'S')
        print("Invalid option!)
        print("Type p or P for a pyramid")
        print("Type s or S for the sum and product of two numbers"
        err_test = sys.stdin.read()
        if err_test == ('p' or 'P' or 's' or 'S')
            break

这段代码大致是我写的。我不是在家里写这个问题,所以我无法逐字复制。如果您发现任何问题,请列出它们,无论是语法错误还是格式错误。我想尽可能多地学习,但是如果您知道为什么评论正下方的行(第 6 行)不起作用,请告诉我!谢谢!

**编辑:**非常感谢您的反馈!但我忘了提及,在某一时刻,我尝试隔离问题,因此我创建了一个新的 python 文件,并创建了一个永久持续的循环,并仅使用一个字符对其进行了测试。我会让它变得超级简化:

char = sys.stdin.read()
if char == 'a':
    print("This works!")
if char != 'a':
    print("This failed!)

即使这个代码^^^也不起作用!请告诉我原因。 –

Backstory: In my previous post, I was wondering if a certain function was valid to replace another function and it was, so, I technically don't need an answer to help with with my project but I was just wondering "had I continued using sys.stdin.read() instead of input(), how would I get through one of my roadblocks?"

My issue: For some reason, when I used sys.stdin.read() it did not work with literal strings or chars. This is a lazy but working reconstruction of my code...

print("Type p or P for a pyramid")
print("Type s or S for the sum and product of two numbers")
choice_1 = sys.stdin.read()

# edge case for inputted char being invalid
if str(choice_1) != ('p' or 'P' or 's' or 'S')
    err_test = 'z'
    while str(err_test) != ('p' or 'P' or 's' or 'S')
        print("Invalid option!)
        print("Type p or P for a pyramid")
        print("Type s or S for the sum and product of two numbers"
        err_test = sys.stdin.read()
        if err_test == ('p' or 'P' or 's' or 'S')
            break

This code is roughly what I wrote. I am not writing this question at home so I couldn't copy it word for word. If you see any problems at all, please list them out, whether it's a syntax error or frowed-upon-formatting. I want to learn as much as possible but please, if you have any idea why the line right below the comment (line 6) doesn't work, please let me know! Thanks!

**Edit: ** Thank you so much for the feedback! I forgot to mention though, at one point, I tried isolating the problem so I created a new python file and created a loop that lasted forever and tested it out with only one character. I'll make it super simplified:

char = sys.stdin.read()
if char == 'a':
    print("This works!")
if char != 'a':
    print("This failed!)

Even this code ^^^ didn't work! Please let me know why. –

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

温柔少女心 2025-01-21 22:25:43

您对“匹配多个接受的字符串之一”的测试是错误的,其方式与这个问题的错误类似;由于使用了括号,它并不完全相同,但在这种情况下,您的两个测试都相当于测试 leftside != 'p',因为 or 链评估到第一个真值,或者最后一个值(如果所有值都是假值),并且任何非空字符串都是真值,因此括号内的分组简化为 'p'。你想要 leftside in ('p', 'P', 's', 'S') (或者在现代 Python 上可能稍微快一点,它优化了针对 set 文字的测试的文字在编译时构造等效的 frozenset 并重用它,从而允许 O(1) 平均情况查找,而不是 O(n) tuple 扫描工作, {'p', 'P', 's', 'S'} 的左侧)。

此外,input 将读取一行,去掉换行符,然后返回它,而 sys.stdin.read() 会消耗 stdin 的全部在第一次调用(所有行)时,将其留空,因此尝试再次调用它将不会收到任何内容。如果由于某种原因您无法使用input,请使用next(sys.stdin).rstrip('\n')或< code>sys.stdin.readline().rstrip('\n') 将大致相当于普通的 input()input 在以下方面更强大)在某些方面,例如它具有 readline 集成,但是很接近)。

最后,一个小注意事项:没有理由执行 str(choice_1)str(err_test) (它们已经是 str,所以换行在 str 中是没有意义的)。

Your test for "matches one of several accepted strings" is wrong in a similar way to this question's mistake; it's not quite the same due to the use of parentheses, but in this case, both of your tests are equivalent to testing leftside != 'p', because or chains evaluate to the first truthy value, or the last value if all are falsy, and any non-empty string is truthy, so the parenthesized grouping simplifies to just 'p'. You wanted leftside in ('p', 'P', 's', 'S') (or perhaps slightly faster on modern Python, which optimizes tests against set literals of literals to construct an equivalent frozenset at compile time and reuse it, allowing O(1) average case lookup, rather than O(n) tuple scan work, leftside in {'p', 'P', 's', 'S'}).

Additionally, input will read one line, strip the newline, and return it, while sys.stdin.read() consumes the entirety of stdin on the first call (all lines), leaving it empty, so trying to call it again will not receive anything. If you can't use input for some reason, either of next(sys.stdin).rstrip('\n') or sys.stdin.readline().rstrip('\n') will be roughly equivalent to plain input() (input is more powerful in some ways, e.g. it has readline integration, but it's close).

Lastly, a minor note: There's no reason to do str(choice_1) or str(err_test) (they're already str, so wrapping in str is pointless).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文