python file.write()在串联字符串中的变量之后添加了一个额外的newline

发布于 2025-01-24 12:30:55 字数 301 浏览 2 评论 0原文

我一直在尝试解决这个问题。我已经写了:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

天气好吗我好吗 2025-01-31 12:30:55

这里发生的事情是,纹理变量可能在其末尾具有一个\ n字符,这是一种使用strip()解决的简单方法。同样,通常建议使用f-strings而不是每次使用 +。解决方案如下:

file.write(f"pyautogui.write('{textEntry.strip()}')")

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:

file.write(f"pyautogui.write('{textEntry.strip()}')")
耳钉梦 2025-01-31 12:30:55

似乎您的textentry变量可能在最后具有newline字符。

您应该尝试从字符串的末端开始剥离新线和空间,如果您想做的就是这样的事情:

file.write("pyautogui.write(" + "'" + textEntry.rstrip() + "'" + ")")

以下是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:

file.write("pyautogui.write(" + "'" + textEntry.rstrip() + "'" + ")")

here is some more info on rstrip: https://stackoverflow.com/a/275025/13282454

节枝 2025-01-31 12:30:55

我认为您的textentry就是这样

    textEntry = '''
text
'''

,因此具有新线。尝试删除它并简单地写

`textEntry='text'`

I think your textEntry is like that

    textEntry = '''
text
'''

so it has a newline. try to remove it and write simply

`textEntry='text'`
走野 2025-01-31 12:30:55

因为在textentry字符串中总是会有一个尾随的newline字符\ n这遗漏了字符串中的最后一个字符:

file.write("pyautogui.write(" + "'" + textEntry[:-1] + "'" + ")")

您还可以使用Python格式的字符串:

file.write(f"pyautogui.write('{textEntry[:-1]}')")

As there will always be a trailing newline character (\n) in the textEntry string, all you'll have to do is use a slice that leaves out the last character in the string:

file.write("pyautogui.write(" + "'" + textEntry[:-1] + "'" + ")")

You can also make use of Python formatted strings:

file.write(f"pyautogui.write('{textEntry[:-1]}')")
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文