Python printing and textwrapping - python

I have a question regarding printing in Python. I use the following for printing
I want to generate a bash script using python 3.7.
res="""\
{someline} some more code some keywords etc
""".format(someline = self.someline)
res = textwrap.dedent(res)
This I use for getting the text in a format that it autmatically prints newlines etc.
But if I now have in my string a lot of arguments, the line gets longer and longer. But if i press enter, I get a newline.
So is there a way to have a wordwrap without having a new line for better
readability in the code?

print("\
This will get printed\
, and this will be on the same line\
")
When using normal quotes, as in " or ', ending a line with a backslash then starting a new line will continue the string over to the next line and not create a new line, which is what you're looking for.

Related

How can I insert a certain character before and after another certain character?

I am writing a short Python 3 program that takes a Python 2 script, and fixes the way Python 2's printing function worked, and fixes it to make it work with Python 3. This is useful for some scripts that use Python 2, but the only issue is that there's tons of incorrect examples of printing according to Python 3.
Example:
Let's say I have a Python 2 script that looks like this:
print 'hello world'
I would want to use my program to convert it to this:
print('hello world')
So far, I have this, which strips the new lines, replaces the first instance of the quotation mark with an opening parenthesis, and replaces the second instance of the quotation mark with a closing parenthesis.
if "print" in ReadNextLine:
RawInput = ReadNextLine.replace(" ", "")
ReadyForFixing = RawInput.strip("\n")
replaceportion1 = ReadyForFixing.replace("'", "(", 1)
replaceportion2 = replaceportion1.replace("'", ")")
print(replaceportion2)
Output:
print(Line1)
print(Line2)
print(Line3)
print(Line4)
print(Line5)
I was wondering if there was some way to insert a quotation mark after the first parenthesis, and before the second parenthesis.
Keep in mind that these outputs will be dynamic according to whatever the file that the user needs fixed inputs.
I plan on posting this project on Github. Let me know if you would like any crediting, since you may have technically collaborated.

Python 2.7 VSCODE doesn't get the correct length of input string

in my class we are studying python 2.7. I am using vscode to test the exercises.
exercise 1: read user input and print the length. If the user write
exit the program finish.
My code is follow:
myexit=False
while (myexit!=True):
#read user input
txt=raw_input("write a string or write exit to go out: ")
#print the user input string
print txt
if (str(txt)=='exit'):
myexit=True#exit from while
else:
print len(txt) #print the string length
print "finish"
when i test the code i get always the length of the string +1
example: if i write foo the output is 4 and no 3. When i write exit i
don't go out from the while and the output is 5.
Where i wrong ?
I have missed a module?
Thanks for your help
I am not sure exactly why this is happening, and I don't have access to a windows machine to test/verify but based on the comments above, it appears that on the version of python you are using that raw_input is only stripping the newline(\n) and not the carriage return(\r). Windows uses \r\n while unix uses \n. When raw input returns the \r is still on the string, hence the extra char. A useful debugging technique at the cli is to use the function repr() on the value to see exactly how it is represented. This is helpful to locate any stray control or invisible chars in strings.
The function rstrip() will remove all whitespace from the right side of the string, which in this case should safely remove the stray \r. It should also be safe if this code is running on a *nix like system as rstrip() will only remove the whitespace if it is present. You can also specify a set of char to strip, so if you would would like to be pedantic, you could use rstrip("\r").
txt=raw_input("write a string or write exit to go out: ").rstrip("\r")
Should fix the issue while still maintaining compatibility on different versions.

Print on a single line not working Python 3

I'm very new to programming and am working on some code to extract data from a bunch of text files. I've been able to do this however the data is not useful to me in Excel. Therefore, I would like to print it all on a single line and separate it by a special character, which I can then delimit in Excel.
Here is my code:
import os
data=['Find me','find you', 'find us']
with open('C:\\Users\\Documents\\File.txt', 'r') as inF:
for line in inF:
for a in data:
string=a
if string in line:
print (line,end='*') #print on same line
inF.close()
So basically what I'm doing is finding if a keyword is on that line and then printing that line if it is.
Even though I have print(,end='*'), I don't get the print on a single line. It outputs:
Find me
*find you
*find us
Where is the problem? (I'm using Python 3.5.1)
Your immediate problem is that you're not removing the newline characters from your lines before printing them. The usual way to do this is with strip(), eg:
print(line.strip(), end='*')
You'll also print multiple copies of the line if more than one of your special phrases appear in the line. To avoid that, add a break statement after your print, or (better, but a more advanced construct that might not make sense until you're used to generator expressions) use if any(keyword in line for keyword in data):
You also don't need to explicitly close the input file - the point of the with open(...) as ...: context manager is that it closes the file when exiting it.
And I would avoid using string as a variable name - it doesn't tell anyone anything about what the variable is used for, and it can cause confusion if you end up using the built-in string module for anything. It's not as bad as shadowing a built-in constructor like list, but it's worth avoiding. Especially since it does nothing for you here, you can just use if a in line: here if you don't want to use the any() version above.
In addition to all that, if your data is not extremely large (and I hope it's not if you're trying to fit it all on one line) you'll get tidier code and avoid the trailing delimiter by using the .join() method on strings, eg something like:
import os
data=['Find me','find you', 'find us']
with open('C:\\Users\\Documents\\File.txt', 'r') as inF:
print "*".join(line.strip() for line in inF if any(keyword in line for keyword in data))

Python variables stored in text files not working, but should be

I've settled on a text-file based save system for my game, storing the values of required variables with keywords - for example, the password that tells the game which chapter to play. However, it appears to be malfunctioning, and I can't see why.
Before starting the game, we have:
if not os.file.isfile('TSGsave{0}.txt'.format(name)):
TSGsave=open('TSGsave{0}.txt'.format(name),'wt')
TSGsave.write('\nw5CT$n<jfW=-#J%4Ya5##')
TSGsave.close()
(the keyword used is a bunch of jibberish so that the user can't change it knowing what's going to happen). This adds w5CT$n<jfW=-#J%4Ya5## to the text file. We then have:
for i in range (len(lines)):
if 'w5CT$n<jfW' in lines[i]:
findpass=lines[i]
for i in range (len(findpass)):
if findpass[i]=='=':
cutfrom=i+1
password=findpass[cutfrom:len(findpass)]
to retrieve the variable (which can change, so it can't be written in as definite value). I know it works, because I added print (password) to the code and it returned -#J%4Ya5##. Then to start the corresponding chapter, the code is:
if password=='-#J%4Ya5##':
but it isn't starting the indented block. In the shell, the program ends and goes back to the >>> line.
If there is a way to fix this code, great - but another code to do the same thing would work just as well.
Your lines contain newlines, and these are being included. Strip these from the line:
findpass = lines[i].rstrip('\n')
Printing a value with a newline in it will simply add an extra black line after the print. Always use the repr() function to produce a Python representation of strings to see such characters:
>>> print '-#J%4Ya5##\n'
-#J%4Ya5##
>>> print repr('-#J%4Ya5##\n')
'-#J%4Ya5##\n'
Your parsing code is overly complicated; you can use str.split() or str.partition() to split your password from the line instead. You should just loop over the lines list directly rather than produce indices with range():
for line in lines:
if 'w5CT$n<jfW' in line:
password = line.partition('=')[2].rstrip('\n')

Removed new line character appears in write to file but not in print to screen

One very stupid thing happens when I modify a string that contained newline characters within it.
After modifying the string variable, I print it. It successfully shows that the new line character has been removed.
When I write the string variable to a file, it prints the new line character there.
I spent hours figuring this out!
import os
import csv
s = "I want this \n new line removed"
s = s.replace("\n", "")
print(s)
file = open('my_file.tsv', 'w')
file.write(s)
file.close()
The above is a sample code. If you run this code, it will run. The string in my real project is a text dynamically fetched from a mysql database -- which is being modified. That contains one or more \n characters within it.
If in the above code, I try replacing that text obtained from the database in a hardcoded manner and running it, it throws me an error saying "EOL while scanning string lateral"
Can you please help me clean this text into something consumable?
Removal of '\r\n' worked!! Thanks a lot #abarnert for the suggestion.
The text wasn't visible to me in code form. It was raw text fetched from db. The raw text just looked like a paragraph with multiple newlines. Hence, I wasn't able to provide real text

Categories