Python如何从sys.stdin.readline()中删除newline



我正在定义一个函数,该函数连接了用户给出的两个字符串,但是sys.stdin.readline((返回的字符串包括newline字符,因此我的输出看起来不显示为串联根本(从技术上讲,此输出仍然是连接的,但是两个字符串之间的" 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

我尝试了读取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))

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

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

最新更新