Python 如何从 sys.stdin.readline() 中删除换行符

Python how to remove newline from sys.stdin.readline()

我正在定义一个连接用户给出的两个字符串的函数,但是 sys.stdin.readline() 返回的字符串包含换行符,所以我的输出看起来根本没有连接(从技术上讲,这输出仍然连接在一起,但两个字符串之间有一个“\n”。)如何去掉换行符?

def concatString(string1, string2):
    return (string1 + string2)

str_1 = sys.stdin.readline()
str_2 = sys.stdin.readline()
print( "%s" % concatString(str_1, str_2))

控制台:

hello
world
hello
world

我试过 read(n) 接受 n 个字符,但它仍然附加了 "\n"

str_1 = sys.stdin.read(5) '''accepts "hello" '''
str_2 = sys.stdin.read(3) '''accepts "\n" and "wo", discards "rld" '''

控制台:

hello
world
hello
wo

您可以将您的 concatString 替换为类似的东西:

def concatString(string1, string2):
    return (string1 + string2).replace('\n','')

只需对从输入中获取的每个字符串调用 strip 即可删除 周围的 个字符。请务必阅读链接的文档以确保要对字符串执行哪种 strip

print("%s" % concatString(str_1.strip(), str_2.strip()))

修复该行和 运行 您的代码:

chicken
beef
chickenbeef

但是,基于您正在接受用户输入这一事实,您可能应该在此处采用更惯用的方法,只使用常用的输入。使用它也不需要您进行任何操作来去除不需要的字符。这是帮助指导您的教程:https://docs.python.org/3/tutorial/inputoutput.html

那么你可以这样做:

str_1 = input()
str_2 = input()

print("%s" % concatString(str_1, str_2))