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

rei*_*mos 5 python string 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))
Run Code Online (Sandbox Code Playgroud)

安慰:

hello
world
hello
world
Run Code Online (Sandbox Code Playgroud)

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

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

安慰:

hello
world
hello
wo
Run Code Online (Sandbox Code Playgroud)

idj*_*jaw 4

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

print("%s" % concatString(str_1.strip(), str_2.strip()))
Run Code Online (Sandbox Code Playgroud)

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

chicken
beef
chickenbeef
Run Code Online (Sandbox Code Playgroud)

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

然后你可以这样做:

str_1 = input()
str_2 = input()

print("%s" % concatString(str_1, str_2))
Run Code Online (Sandbox Code Playgroud)