python file.write()在串联字符串中的变量之后添加了一个额外的newline
我一直在尝试解决这个问题。我已经写了:
file.write("pyautogui.write(" + "'" + textEntry + "'" + ")")
但是在写入的文件中,写下了以下内容:
pyautogui.write('test
')
我希望一切都在一行。有人知道原因吗?我尝试修复它,但无济于事。
I have been trying to solve this issue. I have written:
file.write("pyautogui.write(" + "'" + textEntry + "'" + ")")
but in the file that is written to, the following is written:
pyautogui.write('test
')
I want it all to be on one line. Does anyone know the cause for this? I have tried fixing it, but to no avail.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这里发生的事情是,纹理变量可能在其末尾具有一个\ n字符,这是一种使用strip()解决的简单方法。同样,通常建议使用f-strings而不是每次使用 +。解决方案如下:
What's happening here is that the textEntry variable likely has a \n character at the end of it, a simple way to solve that is by using strip(). Also, it is generally recommended to use f-Strings instead of doing the + each time. A solution is as follows:
似乎您的
textentry
变量可能在最后具有newline字符。您应该尝试从字符串的末端开始剥离新线和空间,如果您想做的就是这样的事情:
以下是RSTRIP上的更多信息: https://stackoverflow.com/a/275025/13282454
it seems like your
textEntry
variable probably has a newline character at the end.you should try stripping newlines and spaces from the end of the string if that is all you want to do so something like:
here is some more info on rstrip: https://stackoverflow.com/a/275025/13282454
我认为您的
textentry
就是这样,因此具有新线。尝试删除它并简单地写
I think your
textEntry
is like thatso it has a newline. try to remove it and write simply
因为在
textentry
字符串中总是会有一个尾随的newline字符(\ n
)这遗漏了字符串中的最后一个字符:您还可以使用Python格式的字符串:
As there will always be a trailing newline character (
\n
) in thetextEntry
string, all you'll have to do is use a slice that leaves out the last character in the string:You can also make use of Python formatted strings: