简体   繁体   English

python 3 输入无换行符

[英]python 3 input without newline

I am new to coding.我是编码新手。 And I would like to know if there's a way for input function to not print newline character after the value is entered.而且我想知道是否有办法输入 function 在输入值后不打印换行符。 Something like print function's argument end.像打印函数的参数结束之类的东西。 Is there any way?有什么办法吗?

Well, you can't make input() trigger by anything besides 'Enter' hit (other way may be using sys.stdin and retrieving character one-by-one until you receive some stop marker, but it's difficult both for programmer and for user, I suppose).好吧,除了“Enter”命中之外,您不能通过任何其他方式触发 input() (其他方式可能是使用 sys.stdin 并一个接一个地检索字符,直到您收到一些停止标记,但这对于程序员和对于用户,我想)。 As a workaround I can the suggest the following: if you can know the length of line written before + length of user input, then you can use some system codes to move cursor back to the end of previous line, discarding the printed newline:作为一种解决方法,我可以提出以下建议:如果您可以知道之前写入的行长度 + 用户输入的长度,那么您可以使用一些系统代码将 cursor 移回上一行的末尾,丢弃打印的换行符:

print("This is first line.")
prompt = "Enter second: "
ans = input(prompt)
print(f"\033[A\033[{len(prompt)+len(ans)}C And the third.")

\033[A moves cursor one line up and \033[<N>C moves cursor N symbols right. \033[A将 cursor 向上移动一行, \033[<N>C将 cursor N 个符号向右移动。 The example code produces the following output:示例代码生成以下 output:

This is first line.
Enter second: USER INPUT HERE And the third.

Also note that the newline character is not printed by your program, it's entered by user.另请注意,换行符不是由您的程序打印的,而是由用户输入的。

name=input('Enter your name: ') print('hello',name,end='') I know about the end function which is abov name=input('Enter your name: ') print('hello',name,end='') 我知道结尾 function 是上面的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM