'Python file.write() is adding an extra newline after a variable in a concatenated string
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.
Solution 1:[1]
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()}')")
Solution 2:[2]
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
Solution 3:[3]
I think your textEntry
is like that
textEntry = '''
text
'''
so it has a newline. try to remove it and write simply
`textEntry='text'`
Solution 4:[4]
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]}')")
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Caden Grey |
Solution 2 | Yash |
Solution 3 | stu_dent |
Solution 4 | Ann Zen |