Skip to main content
 首页 » 编程设计

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

2024年10月01日9cyq1162

我正在定义一个连接用户给出的两个字符串的函数,但是 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 

请您参考如下方法:

只需调用 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))