输出字符串中不必要的新行,Python,如何去掉这些换行符?

2024-09-29 20:19:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个用户.txt包括以下内容:

user1:M0024132132

user2:M00123132

user3:M001234123

user4:123123

我编写了一个python代码来执行基本的字符串连接操作

^{pr2}$

预期产量:

create:user:M00123132:::user:/home/user:/bin/bash::::: create:user1:M00123132:::user1:/home/user1:/bin/bash::::: create:useruser1:M00212312:::useruser1:/home/useruser1:/bin/bash::::: create:sdfsdf:12312:::sdfsdf:/home/sdfsdf:/bin/bash:::::

但我得到的输出是:

create:user:M00123132

:::user:/home/user:/bin/bash:::::

create:user1:M00123132

:::user1:/home/user1:/bin/bash:::::

create:useruser1:M00212312

:::useruser1:/home/useruser1:/bin/bash:::::

请帮我解决这个问题。在


Tags: 用户txtbashhomebincreateuseruser1
2条回答

在Python3中,可以使用^{}关键字参数来取消换行:

print ('create:' + str(user) + ':' + str(passwd) + ':::' + str(user) 
       + ':/home/' + str(user) + ':/bin/bash:::::', end="")

顺便说一下,您可以简单地使用:

^{pr2}$

而不是使用中间列表变量(即sout)。在

你需要把这条线剥掉才能去掉新的线。readlineapi读取新行。这一新行后来成为passwd变量的一部分。在

while line:
    line = line.strip()

来自Python文档:https://docs.python.org/2/tutorial/inputoutput.html

f.readline() reads a single line from the file; a newline character (\n) is left at the end of the string, and is only omitted on the last line of the file if the file doesn’t end in a newline.

相关问题 更多 >

    热门问题