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

4

我正在定义一个函数,该函数将用户提供的两个字符串连接在一起,但由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

1
为什么不直接使用 input(即在 Python 2 中使用 raw_input)? - juanpa.arrivillaga
2个回答

4

从输入中获得每个字符串后,只需调用strip函数即可去除字符串的前后空格。请确保阅读链接文档以确定您想要在字符串上执行的剥离类型。

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

修复那一行并运行你的代码:

chicken
beef
chickenbeef

然而,基于你正在使用用户输入,你应该采用更为惯用的方式,直接使用常用的input函数。这样做也无需进行任何操作以剥离不需要的字符。以下是有关此方面的教程,可供参考:

https://docs.python.org/3/tutorial/inputoutput.html

然后,你只需执行以下操作:

str_1 = input()
str_2 = input()

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

谢谢!我刚开始学习Python,还在熟悉函数。干杯! - reiallenramos
1
请记住,不带参数的 strip() 会删除字符串开头和结尾的所有空格。如果只想删除字符串末尾的空格,请使用 rstrip();如果只想删除换行符,请使用 rstrip('\n') - Graham Dumpleton

1
你可以将 concatString 替换为类似以下的内容:
def concatString(string1, string2):
    return (string1 + string2).replace('\n','')

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接