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? )
Related
I recently read about how to type one letter at a time in Python to look old school and cool using loops and time - however, my code has an input. Does anyone know how to do this for and input (in my code , "what is your name?")
I've tried changing the input name but has failed. The code simply prints it at once like usual
If you are looking to do something that looks like this:
Then the easiest way is to do it as it was done back in the good old days. What happened then was that the program would send special codes to the terminal (which back then was a real physical device, not just a window), and the terminal would do whatever codes wanted. There were codes for moving the cursor around, changing colors, beeping and lots of other nifty stuff that you would need.
A common set of codes that still are in use today are known as the ANSI escape codes.
There is an excellent package called Colorama for Python that does all of the heavy-lifting and that is cross-platform. I recommend using that.
Source code for the demo above:
from colorama import init, Fore, Style
import time
def print_old(message):
print(Fore.GREEN, end='', flush=True)
for c in message:
print(c, end='', flush=True)
time.sleep(0.1)
print(Style.RESET_ALL, end='', flush=True)
init()
print_old('What is your name? ')
name = input()
print_old('Nice to meet you %s\n' % name)
Hopefully this is what you are looking for.
This makes it look like what you're talking about
import time
output = "what is your name?"
blank = ""
for i in output:
blank = blank + i
print("\r"+blank, end='')
time.sleep(0.1)
x = input()
The idea is to build larger and larger portions of your output and using the \r you replace the line in the console each time. Waiting 0.1 seconds between loops adds to the effect
If I understand correctly what you are asking, you can print each letter and use input at the end.
Something like this:
output = "what is your name?"
for i in output:
print(i, end='')
x = input()
x will be the string containing what the user inputs.
Imho, it's not cool, just redundant.
If you want a delay between the appearance of each letter, use the time module.
import sys
import time
output = "what is your name?"
for i in output:
print(i, end='')
sys.stdout.flush()
time.sleep(0.1)
x = input()
Note the use of sys.stdout.flush() to push each letter immediately in the output.
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)
I have this code (test.py) below:
import sys
for str in sys.stdin.readline():
print ('Got here')
print(str)
For some reason when I run the program python test.py and then I type in abc into my terminal I get this output:
>>abc
THIS IS THE OUTPUT:
Got here
a
Got here
b
Got here
c
Got here
It prints out Got here five times and it also prints out each character a, b, c individually rather than one string like abc. I am doing sys.stdin.readline() to get the entire line but that doesn't seem to work either. Does anyone know what I am doing wrong?
I am new to python and couldn't find this anywhere else on stackoverflow so sorry if this is a obvious question.
readline() reads a single line. Then you iterate over it. Iterating a string gives you the characters, so you are running your loop once for each character in the first line of input.
Use .readlines(), or better, just iterate over the file:
for line in sys.stdin:
But the best way to get interactive input from stdin is to use input() (or raw_input() in Python 2).
You are looping through each character in the string that you got inputted.
import sys
s = sys.stdin.readline()
print ('Got here')
print(s)
# Now I can use string `s` for whatever I want
print(s + "!")
In your original code you got a string from stdin and then you looped through ever character in that input string and printed it out (along with "Got here").
EDIT:
import sys
while True:
s = sys.stdin.readline()
# Now I can do whatever I want with string `s`
print(s + "!")
I'm making a basic utility in Python 3 where the user inputs a command and gets feedback printed out into the console. When entering data using the input() or sys.stdin.readline() functions this is what the command-line session may look like (including \r and \n characters)
1. What is your name:\n
2. <user input>\n
3. Your name is <variable>.\n
But, I would like to display a \r character after the user hits enter instead of the \n character, as shown on line 2. After the user had typed everything in and hit enter it would look like this
1. What is your name:\n
2. Your name is <variable>.\n
(because line 2 would have a \r character after the entered data, returning the cursur back to the far left)
Does anybody know of a way I might accomplish this?
Well, I discovered this method although I am almost cirtain that the msvcrt module is for Windows only.
import msvcrt
import sys
def msgInput(prompt):
print(prompt, end='')
data= b''
while True:
char= msvcrt.getch()
if char != b'\r':
print(char.decode(), end='')
sys.stdout.flush()
data= data+char
else:
print('\r', end='')
break
return data.decode()
If anybody knows of any cross-platform methods, please share.
Update - Unfortunately this method has many limitations, such as the user cannot navigate the entered text with the arrow keys.
Well, I believe I found the solution you wanted:
strng=input("Enter String - ")
Where strng is just a variable to hold the input response. This will return the string in the interpreter Enter String - (without any quote) and allow you to save the response in the variable strng.
I made a python script to take text from an input file and randomly rearrange the words for a creative writing project based around the cut-up technique (http://en.wikipedia.org/wiki/Cut-up_technique).
Here's the script as it currently stands. NB: I'm running this as a server side include.
#!/usr/bin/python
from random import shuffle
src = open("input.txt", "r")
srcText = src.read()
src.close()
srcList = srcText.split()
shuffle(srcList)
cutUpText = " ".join(srcList)
print("Content-type: text/html\n\n" + cutUpText)
This basically does the job I want it to do, but one improvement I'd like to make is to identify duplicate words within the output and remove them. To clarify, I only want to identify duplicates in a sequence, for example "the the" or "I I I". I don't want to make it so that, for example, "the" only appears once in the entire output.
Can someone point me in the right direction to start solving this problem? (My background isn't in programming at all, so I basically put this script together through a lot of reading bits of the python manual and browsing this site. Please be gentle with me.)
You can write a generator to produce words without duplicates:
def nodups(s):
last = None
for w in s:
if w == last:
continue
yield w
last = w
Then you can use this in your program:
cutUpText = " ".join(nodups(srcList))
Adding the lines
spaces = [(i%10) == 9 and '\n' or ' ' for i in range(0,len(srcList))];
cutUpText = "".join(map(lambda x,y: "".join([x,y]),srcList,spaces));
helps bring some raw formatting to the text screens.
Add this to your existing program:
srcList = list(set(srcText.split()))