print() prints only every second input - python

I'm new to python and I've been trying to make a little function to call upon when I need to filter an input from everything except regular letters.
I've used SO for parts of the code, but I can't seem to understand why does it only print on every second try.
Here's my code:
import re
i=1
def inputFilterText():
inputRaw = input('input: ')
inputFiltered = re.sub('[^a-zA-Z]+', '', inputRaw)
return inputFiltered
while i > 0:
inputFilterText()
print(inputFilterText())
And here's my output:
I'm not really sure what's going on, but I presume it's a logical error. I've only just started using Python so any help is appreciated.
PSThe 'while' is only there so it's easier to test, it can be omitted.

You are calling inputFilterText twice. Once within the print() and once before. This is causing the code to prompt for input twice before printing the second response.

The problem is that you make a call to the inputFilterText function twice. The first time the output is discarded. Causing input to be taken twice, but only showing a result once.
To fix it, remove the inputFilterText() line. An example of working code.
import re
i=1
def inputFilterText():
inputRaw = input("input: ")
inputFiltered = re.sub(""[^a-zA-Z]+, "", inputRaw)
return inputFiltered
while i > 0:
print(inputFilterText())
Also, in future please send code as raw text, rather than screenshots.

Might I suggest using a variable here, you're not doing anything with the first filter call (this is why it's asking the first time) and the second one you're only printing.
while True:
txt = inputFilterText()
#do some stuff if needed
print(txt)

Related

Simple Python string code\decode script question

I'm learning Python and for my homework I wrote a simple script that get a string from user like this one: aaaabbbbcccdde and transforms it to a4b4c3d2e1.
Now I've decided to get things more interesting and modified code for continuous input and output in realtime. So I need a possibility to enter symbols and get an output coded with that simple algorithm.
The only problem I've faced with I needed output without '\n' so all the coded symbols were printed consequently in one string e.g: a4b4c3d2e1
But in that case output symbols mixed with my input and eventually the script froze. Obviously I need Enter symbols for input on one string and output it on another string w/o line breaks.
So, could you tell me please is it possible without a lot of difficulties for newbie make up a code that would do something like this:
a - #here the string in shell where I'm always add any symbols
a4b4c3d2e1a4b4c3d2e1a4b4c3d2e1 - #here, on the next string the script continuously outputs results of coding without breaking the line.
import getch
cnt = 1
print('Enter any string:')
user1 = getch.getch()
while True:
buf = getch.getch()
if buf == user1:
cnt += 1
user1 = buf
else:
print(user1, cnt, sep='')
user1 = buf
cnt = 1
so this snippet outputs me something like this:
a4
s4
d4
f4
etc
And in all cases when I'm trying to add end='' to output print() the program sticks.
What is possible to do to get rid of that?
Thanks !
I don't really know the details but I can say that: when you add end='', the program don't freeze, but the output (stdout) does not refresh (maybe due to some optimisation ? I really don't know).
So what you want to do is to flush the output right after you print in it.
print(user1, cnt, sep='', end='')
sys.stdout.flush()
(It is actually a duplicate of How to flush output of print function? )

Expecting a certain format

So i'm trying to write a code for a router terminal simulator. And I'm using raw_input to read from the keyboard.
The problem is that I want to do a specific action when the user writes a sequence that matches this pattern: "<1-100> permit", so in order to accomplish this I wrote an if of this type:
if input == "%d permit" %number:
print 'Do this'
I want the number to be a value in the range of 1-100. I created a list with the range(1,100) function but I don't know how to check this condition inside my if.
I solved the problem however with the use of split function and some other conditions, but I can't really get over this idea and I want to find a solution. Any help would be greatly appreciated.
if input == "%d permit" %number and number in range(1,101):
print 'Do this'
Use re.match(pattern, value):
import re
[...]
if re.match(r"(\d\d?|100) permit", input):
do_something()
And the variable input will override the built-in function input(), so change the name to something else.
EDIT: As you don't want to use RegExp, you can split the string, pass it to int and then see if it's in the range.
if 1 <= int(input.split(" ")[0]) <= 100:
do_something()

Function is not being called after input assigns a value (Python)

I have a small file with a bunch of phrases on each line. I want the user to type a number and that number will print the selected line.
def printSpecLine(x):
print('started')
with open('c:/lab/save.txt') as f:
for i, line in enumerate(f, 1):
if i == x:
break
print (line)
print('done')
f.close()
s = int(input("Enter a number: "))
printSpecLine(s)
I've ran this with no errors, but the function isn't being called at all. Printing "started" (second line) didn't even occur. Am I missing a step here?
The only explanation for this is that you are not actually inputting to the prompt! There doesn't seem to be any other reason why at least the first print wouldn't be made.
Remember that input() is blocking, so until you enter your number and press enter, the program will be halted where it is (i.e. not call the function).
Apparently the ide i was using has a problem with raw input and integers being converted. Sublime Text 3 doesn't take python input very well. Thank you for your answer.

Overwrite previous output on same line

I want the output of my code to overwrite the previous output on the same line.
I have read the previous answers to a similar question and have read that I can do this using a ',' and a '\r', but this doesn't seem to work for me. I tried:
for i in range(length):
print 'Minutes:',minute,'of {0}'.format(length),'\r',
minute+=1
time.sleep(1)
But it doesn't print anything other than the last line of the loop. I've tried other arrangements,but nothing yet has worked. Could someone let me know what I'm doing wrong?
Thanks.
If You are doing this in Linux, You can simply use ASCII escape sequence to move cursor up one line (\033[1A). Of course, You will still use \r to move to the beginning of the line. You could use something like this:
for i in range(length):
print('Minutes: ' + minutes + '\033[1A\r')
minutes += 1
sleep(1)
You need sys.stderr for fast output on a screen:
import sys,time
length,minute = 10,0
for i in range(length):
sys.stderr.write('Minutes:{} of {}\r'.format(minute,length))
minute+=1
time.sleep(1)
Don't forget to add sys.stderr.write('\n') at the end of your loop to avoid printing into the same line.
The easiest way I can think of doing this is, if you know how many lines your shell is, then you can just
print "\n" * (number_of_lines - 1)
then
print 'Minutes:',minute,'of {0}'.format(length)
So together,
for i in range(length):
print "\n" * (number_of_lines - 1)
print 'Minutes:',minute,'of {0}'.format(length)
minute += 1
time.sleep(1)
General Tips
You use commas and str.format() in the same print statement, instead just use str.format() for all of it. e.g print 'Minutes: {0}, of {1}'.format(minute, length).
You used minute as your counter even though it appears you are counting by seconds. For clarity you may want to rename that variable second.
Note
sys.stderr is the better way to do this. Please look at rth's answer
If you are using Python3, you can use a code like this:
import time
minute, length = 1, 100
for i in range(length):
print ('Minutes: {0} of {1}\r'.format(minute, length), end = "")
minute+=1
time.sleep(1)
However if you are using Python2, you can import print_function from __future__ module like this example:
from __future__ import print_function
import time
minute, length = 1, 100
for i in range(length):
print("Minutes: {0} of {1}\r".format(minute, length), end = "")
minute+=1
time.sleep(1)
PS: I have a strange issue when running the last code from my terminal using Python2.7.10. The script work but there is not any output.
However within Python 2.7.10 interpreter the code works fine.
Test both solutions and leave your feedbacks if you encounter any problems within Python2.
EDIT:
I think the better solution to avoid the strange issue that i encounter, and i don't know the cause, is using the ASCII escape as #Fejs said in his answer.
Your code will be something like this:
import time
minute, length = 1, 100
for i in range(length):
print "Minutes: {0} of {1} {2}".format(minute, length, '\033[1A\r')
minute+=1
time.sleep(1)
Try flushing the output before each sleep.
minute+=1
sys.stdout.flush()
time.sleep(1)

Incorporating multiple lists in one text file

I am new to coding and I ran in trouble while trying to make my own fastq masker. The first module is supposed to trim the line with the + away, modify the sequence header (begins with >) to the line number, while keeping the sequence and quality lines (A,G,C,T line and Unicode score, respectively).
class Import_file(object):
def trim_fastq (self, fastq_file):
f = open('path_to_file_a', 'a' )
sanger = []
sequence = []
identifier = []
plus = []
f2 = open('path_to_file_b')
for line in f2.readlines():
line = line.strip()
if line[0]=='#':
identifier.append(line)
identifier.replace('#%s','>[i]' %(line))
elif line[0]==('A' or 'G'or 'T' or 'U' or 'C'):
seq = ','.join(line)
sequence.append(seq)
elif line[0]=='+'and line[1]=='' :
plus.append(line)
remove_line = file.writelines()
elif line[0]!='#' or line[0]!=('A' or 'G'or 'T' or 'U' or 'C') or line[0]!='+' and line[1]!='':
sanger.append(line)
else:
print("Danger Will Robinson, Danger!")
f.write("'%s'\n '%s'\n '%s'" %(identifier, sequence, sanger))
f.close()
return (sanger,sequence,identifier,plus)
Now for my question. I have ran this and no error appears, however the target file is empty. I am wondering what I am doing wrong... Is it my way to handle the lists or the lack of .join? I am sorry if this is a duplicate. It is simply that I do not know what is the mistake here. Also, important note... This is not some homework, I just need a masker for work... Any help is greatly appreciated and all mentions of improvement to the code are welcomed. Thanks.
Note (fastq format):
#SRR566546.970 HWUSI-EAS1673_11067_FC7070M:4:1:2299:1109 length=50
TTGCCTGCCTATCATTTTAGTGCCTGTGAGGTGGAGATGTGAGGATCAGT
+
hhhhhhhhhhghhghhhhhfhhhhhfffffe`ee[`X]b[d[ed`[Y[^Y
Edit: Still unable to get anything, but working at it.
Your problem is with your understanding of the return statement. return x means stop executing the current function and give x back to whoever called it. In your code you have:
return sanger
return sequence
return identifier
return plus
When the first one executes (return sanger) execution of the function stops and sanger is returned. The second through fourth return statements never get evaluated and neither does your I/O stuff at the end. If you're really interested in returning all of these values, move this after the file I/O and return the four of them packed up as a tuple.
f.write("'%s'\n '%s'\n '%s'" %(identifier, sequence, sanger))
f.close()
return (sanger,sequence,identifier,plus)
This should get you at least some output in the file. Whether or not that output is in the format you want, I can't really say.
Edit:
Just noticed you were using /n and probably want \n so I made the change in my answer here.
You have all sorts of errors beyond what #Brian addressed. I'm guessing that your if and else tests are trying to check the first character of line? You'd do that with
if line[0] == '#':
etc.
You'll probably need to write more scripts soon, so I suggest you work through the Python Tutorial so you can get on top of the basics. It'll be worth your while.

Categories

Resources