My idea was to insert a line of slow-moving text into a set of printed text after the printed text had finished printing out.
So for example:
##############
# SlowText #
##############
The border would be printed out immediately and then the SlowText would appear after a short period, writing out slowly.
I've tried a couple of different slow-moving text snippets to perform the actual writing. like:
def print_slow(txt):
for x in txt:
print(x, end='', flush=True)
sleep(0.1)
and
def insertedtext():
text = " E..n..j..o..y..."
for character in text:
sys.stdout.write(character)
sys.stdout.flush()
time.sleep(0.05)
I've tried using '#'+ words + '#' , tried throwing another print("words") in there. Heck, I even attemped at making it a variable but since I am quite new to Python I just can seem to figure it out or google it correctly enough to find it on my own. Any/all help appricated.
I think this is what your looking for :
from time import sleep
def make_box (character, width) :
print (character * (width + 4))
print (character + ' ' * (width + 2) + character)
print (character * (width + 4))
def print_slow (character, text):
print ('\033[2A' + character, end = ' ')
for x in text:
print (x, end='', flush=True)
sleep (0.1)
print ()
box_character = '#'
text = 'This is a test'
make_box (box_character, len (text))
print_slow (box_character, text)
The line print ('\033[2A... moves the cursor up two lines.
Related
My desired output is two half pyramids separated by two spaces.
length = int(input("Enter size of pyramid."))
hashes = 2
for i in range(0, length):
spaces = length - (i+1)
hashes = 2+i
print("", end=" "*spaces)
print("#", end=" "*hashes)
print(" ", end="")
print("#" * hashes)
However, this ends up printing only the first hashes of each row on the left pyramid. If I get rid of the end= in line 7, the pyramids are both printed correctly, but with newlines after each row. Here are the outputs:
With end=:
# ##
# ###
# ####
# #####
Without end=:
##
##
###
###
####
####
#####
#####
All I want now is to have the second output, but without the newlines.
The most straightforward way to print any output you want without newlines is to uses sys.stdout.write. This writes a string to the stdout without appending a new line.
>>> import sys
>>> sys.stdout.write("foo")
foo>>> sys.stdout.flush()
>>>
As you can see above, "foo" is written with no newline.
You're multiplying the end parameter by the number of hashes, instead of multiplying the main text portion.
Try this modification:
length = int(input("Enter size of pyramid."))
hashes = 2
for i in range(0, length):
spaces = length - (i+1)
hashes = 2+i
print(" " * spaces, end="")
print("#" * hashes, end="")
print(" ", end="")
print("#" * hashes)
Try this algorithm:
length = int(input("Enter size of pyramid."))
# Build left side, then rotate and print all in one line
for i in range(0, length):
spaces = [" "] * (length - i - 1)
hashes = ["#"] * (1 + i)
builder = spaces + hashes + [" "]
line = ''.join(builder) + ''.join(builder[::-1])
print(line)
for index in range(0, len(order_of_fruits)):
maze[prevY][prevX] = ' '
curr = order_of_fruits[index]
maze[curr[1]][curr[0]] = 'P'
prevX = curr[0]
prevY = curr[1]
result_maze = ""
for i in range(len(maze)):
for j in range(len(maze[0])):
result_maze = result_maze + maze[i][j]
result_maze = result_maze + '\n'
animation.append(result_maze)
#animate
for index in range(0, len(animation)):
time.sleep(0.2)
sys.stdout.write("\r" + str(animation[index]))
sys.stdout.flush()
Hi, my problem is that I have a two-dimentionay array whose condition will update. Then I convert each updated array to a string and append each string to a list which are used to print in the console. Now I want print the changing condition of this maze which have already been converted to string in place. I used the "\r" and flush but it does not work. I guess this might because I have "\n" in each of my string. So is there any way that I can print the series of maze in console in place? So the result looks like only one maze appears on the console whose condition will update every 0.2?
Thanks!
"\r" maybe put in the end of line.
import time
for index in range(0, len(animation)):
sys.stdout.write(str(animation[index]) + "\r")
sys.stdout.flush()
time.sleep(0.2)
You might consider using the curses module. This program updates the screen, waits 0.2 seconds, and updates the screen again:
from curses import wrapper
import time
def main(stdscr):
stdscr.clear()
for i in range(5):
for y in range(5):
for x in range(5):
stdscr.addstr(y, x, chr(ord('1')+i))
stdscr.refresh()
time.sleep(0.2)
stdscr.getkey()
wrapper(main)
I'm a beginner in coding and in Python too. Right now I'm working on a Vigenère cipher.
I've gotten far enough to encrypt the message using a key. I added comments on each section of code for reference. Here is my code. My question is below the code.
# Ask user for message
print('type a message.')
message = input()
# print a white line for neatness
print()
# ask user for a key
print('give your key')
key = input()
# create a range with the length of the message
ran = range(len(message))
# Iterate though the range and therefor show all the letters
for i in ran:
# get current letters for this iteration
currentLetter = message[i]
currentKeyLetter = key[i % len(key)]
# Get corresponding numbers
numberLetter = ord(currentLetter)
numberKeyLetter = ord(currentKeyLetter)
# Add two letters
sumTwoLetters = numberLetter + numberKeyLetter
# Get the number of the encrypted letter
newNumberLetter = sumTwoLetters % 128
# Get the encrypted number based on number
newLetter = chr(newNumberLetter)
# print out the result
printText = currentLetter + "(" + str(numberLetter) + ") + "
printText += currentKeyLetter + "(" + str(numberKeyLetter) + ") = "
printText += newLetter + "(" + str(newNumberLetter) + ")"
print(printText)
The code asks for the user's input for the message and key. The ran variable creates a range with the length of the message.
After that, the for loop encrypts the message with the key using ord and chr
The encrypted letter is stored in the variable newLetter
the user can see what the program has done with printText
However, my question is: How can I make the encrypted text appear on a single string. I tried to do it in a loop. I failed miserably (so much so that I don't want to show it)
Does anyone have any suggestions on how to make the encrypted message appear in a single line of text?
You can gather the results in a list and then join() them all into a single string at the end after the for loop. See the comments for the changes.
...
results = [] # ADDED.
# Iterate though the range and therefor show all the letters
for i in ran:
# get current letters for this iteration
currentLetter = message[i]
currentKeyLetter = key[i % len(key)]
# Get corresponding numbers
numberLetter = ord(currentLetter)
numberKeyLetter = ord(currentKeyLetter)
# Add two letters
sumTwoLetters = numberLetter + numberKeyLetter
# Get the number of the encrypted letter
newNumberLetter = sumTwoLetters % 128
# Get the encrypted number based on number
newLetter = chr(newNumberLetter)
# print out the result
printText = currentLetter + "(" + str(numberLetter) + ") + "
printText += currentKeyLetter + "(" + str(numberKeyLetter) + ") = "
printText += newLetter + "(" + str(newNumberLetter) + ")"
results.append(printText) # PUT IN results LIST INSTEAD OF PRINTING.
print(''.join(results)) # ADDED.
There are two easy ways. Either (1) build the string inside the loop and print it outside the loop, or (2) print each character as you move through the loop but without newlines, plus one newline after the loop.
Try one of those approaches and if you need more help, add a comment. You'll learn more by trying it yourself!
I've written a small script that creates a new line break after a certain character limit has been reached. Now the problem is that the script outputs the text starting at the end of the text. I can't seem to figure out how to make the text print out in the correct order without making the script more complicated. I'm doing this an exercise to better understand recursion.
Here is the code:
def insertNewlines(text, lineLength):
if len(text) <= lineLength:
return text
else:
return insertNewlines(text[lineLength:], lineLength) + '\n' + text[:lineLength]
Here is the test output for a lineLength of 15:
length.
e desired line
s or exceeds th
ord that reache
n' after each w
e character '\
Insert a newlin
ewriter would.
e text as a typ
length, wrap th
a desired line
Given text and
The actual input:
text = "Given text and a desired line length, wrap the text as a typewriter would. Insert a newline character '\\n' after each word that reaches or exceeds the desired line length."
EDIT:
Modified the code based on the suggestion below so that it wraps the words correctly:
if len(text) <= lineLength:
return text
elif text[lineLength] != ' ':
return insertNewlines(text[:], lineLength + 1)
else:
return text[:lineLength] + '\n' + insertNewlines(text[lineLength + 1:], lineLength)
Here is the new output:
Given text and a
desired line length,
wrap the text as a typewriter
would. Insert a newline character
'\n' after each word that reaches
or exceeds the desired line length.
If you don't want the words to be cut off at your max width, try the textwrap library, see http://docs.python.org/2/library/textwrap.html
from textwrap import TextWrapper
text = "Given text and a desired line length, wrap the text as a typewriter would. Insert a newline character '\\n' after each word that reaches or exceeds the desired line length."
tw = TextWrapper()
tw.width = 20
print "\n".join(tw.wrap(text))
[out]:
Given text and a
desired line length,
wrap the text as a
typewriter would.
Insert a newline
character '\n'
after each word that
reaches or exceeds
the desired line
length.
Here's a native python implementation:
text = "Given text and a desired line length, wrap the text as a typewriter would. Insert a newline character '\\n' after each word that reaches or exceeds the desired line length."
def wrap(txt, width):
tmp = ""
for i in txt.split():
if len(tmp) + len(i) < width:
tmp+=" "+i
else:
print tmp.strip()
tmp = i
wrap(text, 20)
a more pythonic yielding method:
def wrap(txt, width):
tmp = ""
for i in txt.split():
if len(tmp) + len(i) < width:
tmp+=" "+i
else:
yield tmp.strip()
tmp = i
print "\n".join(i for i in wrap(text, 20))
The problem is with the order of recursive call. It should be at the tail of the function to achieve what you want. Try this:
def insertNewlines(text, lineLength):
if len(text) <= lineLength:
return text
else:
return text[:lineLength] + '\n' + insertNewlines(text[lineLength:], lineLength)
text = "Given text and a desired line length, wrap the text as a typewriter would. Insert a newline character '\\n' after each word that reaches or exceeds the desired line length."
print insertNewlines(text, 15)
Output:
Given text and
a desired line
length, wrap th
e text as a typ
ewriter would.
Insert a newlin
e character '\
n' after each w
ord that reache
s or exceeds th
e desired line
length.
Firt thing I'd like to say is this place has helped me more than I could ever repay. I'd like to say thanks to all that have helped me in the past :).
I am trying to devide up some text from a specific style message. It is formated like this:
DATA|1|TEXT1|STUFF: some random text|||||
DATA|2|TEXT1|THINGS: some random text and|||||
DATA|3|TEXT1|some more random text and stuff|||||
DATA|4|TEXT1|JUNK: crazy randomness|||||
DATA|5|TEXT1|CRAP: such random stuff I cant believe how random|||||
I have code shown below that combines the text adding a space between words and adds it to a string named "TEXT" so it looks like this:
STUFF: some random text THINGS: some random text and some more random text and stuff JUNK: crazy randomness CRAP: such random stuff I cant believe how random
I need it formated like this:
DATA|1|TEXT1|STUFF: |||||
DATA|2|TEXT1|some random text|||||
DATA|3|TEXT1|THINGS: |||||
DATA|4|TEXT1|some random text and|||||
DATA|5|TEXT1|some more random text and stuff|||||
DATA|6|TEXT1|JUNK: |||||
DATA|7|TEXT1|crazy randomness|||||
DATA|8|NEWTEXT|CRAP: |||||
DATA|9|NEWTEXT|such random stuff I cant believe how random|||||
The line numbers are easy, I have that done as well as the carraige returns. What I need is to grab "CRAP" and change the part that says "TEXT1" to "NEWTEXT".
My code scans the string looking for keywords then adds them to their own line then adds text below them followed by the next keyword on its own line etc. Here is my code I have so far:
#this combines all text to one line and adds to a string
while current_segment.move_next('DATA')
TEXT = TEXT + " " + current_segment.field(4).value
KEYWORD_LIST = [STUFF:', THINGS:', JUNK:']
KEYWORD_LIST1 = [CRAP:']
#this splits the words up to search through
TEXT_list = TEXT.split(' ')
#this searches for the first few keywords then stops at the unwanted one
for word in TEXT_list:
if word in KEYWORD_LIST:
my_output = my_output + word
elif word in KEYWORD_LIST1:
break
else:
my_output = my_output + ' ' + word
#this searches for the unwanted keywords leaving the output blank until it reaches the wanted keyword
for word1 in TEXT_list:
if word1 in KEYWORD_LIST:
my_output1 = ''
elif word1 in KEYWORD_LIST1:
my_output1 = my_output1 + word1 + '\n'
else:
my_output1 = my_output1 + ' ' + word1
#my_output is formatted back the way I want deviding up the text into 65 or less character lines
MAX_LENGTH = 65
my_wrapped_output = wrap(my_output,MAX_LENGTH)
my_wrapped_output1 = wrap(my_output1,MAX_LENGTH)
my_output_list = my_wrapped_output.split('\n')
my_output_list1 = my_wrapped_output1.split('\n')
for phrase in my_output_list:
if phrase == "":
SetID +=1
output = output + "DATA|" + str(SetID) + "|TEXT| |||||"
else:
SetID +=1
output = output + "DATA|" + str(SetID) + "|TEXT|" + phrase + "|||||"
for phrase2 in my_output_list1:
if phrase2 == "":
SetID +=1
output = output + "DATA|" + str(SetID) + "|NEWTEXT| |||||"
else:
SetID +=1
output = output + "DATA|" + str(SetID) + "|NEWTEXT|" + phrase + "|||||"
#this populates the fields I need
value = output
Then I format the "my_output" and "my_output1" adding the word "NEWTEXT" where it goes. This code runs through each line looking for the keyword then puts that keyword and a carraige return in. Once it gets the other "KEYWORD_LIST1" it stops and drops the rest of the text then starts the next loop. My problem is the above code gives my this:
DATA|1|TEXT1|STUFF: |||||
DATA|2|TEXT1|some random text|||||
DATA|3|TEXT1|THINGS: |||||
DATA|4|TEXT1|some random text and|||||
DATA|5|TEXT1|some more random text and stuff|||||
DATA|6|TEXT1|JUNK: |||||
DATA|7|TEXT1|crazy randomness|||||
DATA|8|NEWTEXT|crazy randomness|||||
DATA|9|NEWTEXT|CRAP: |||||
DATA|10|NEWTEXT|such random stuff I cant believe how random|||||
It is grabbing the text from before "KEYWORD_LIST1" and adding it into the NEWTEXT section. I know there is a way to make groups from the keyword and text after it but I am unclear on how to impliment it. Any help would be much appreciated.
Thanks.
This is what I had to do to get it to work for me:
KEYWORD_LIST = ['STUFF:', 'THINGS:', 'JUNK:']
KEYWORD_LIST1 = ['CRAP:']
def text_to_message(text):
result=[]
for word in text.split():
if word in KEYWORD_LIST or word in KEYWORD_LIST1:
if result:
yield ' '.join(result)
result=[]
yield word
else:
result.append(word)
if result:
yield ' '.join(result)
def format_messages(messages):
title='TEXT1'
for message in messages:
if message in KEYWORD_LIST:
title='TEXT1'
elif message in KEYWORD_LIST1:
title='NEWTEXT'
my_wrapped_output = wrap(message,MAX_LENGTH)
my_output_list = my_wrapped_output.split('\n')
for line in my_output_list:
if line = '':
yield title + '|'
else:
yield title + '|' + line
for line in format_messages(text_to_message(TEXT)):
if line = '':
SetID +=1
output = "DATA|" + str(SetID) + "|"
else:
SetID +=1
output = "DATA|" + str(SetID) + "|" + line
#this is needed instead of print(line)
value = output
General tip: Don't try to build up strings accretively like this:
my_output = my_output + ' ' + word
instead, make my_output a list, append word to the list, and
then, at the very end, do a single join: my_output = '
'.join(my_output). (See text_to_message code below for an example.)
Using join is the right way to build strings. Delaying the creation of the string is useful because processing lists of substrings is more pleasant than splitting and unsplitting strings, and having to add spaces and carriage returns here and there.
Study generators. They are easy to understand, and can help you a lot when processing text like this.
import textwrap
KEYWORD_LIST = ['STUFF:', 'THINGS:', 'JUNK:']
KEYWORD_LIST1 = ['CRAP:']
def text_to_message(text):
result=[]
for word in text.split():
if word in KEYWORD_LIST or word in KEYWORD_LIST1:
if result:
yield ' '.join(result)
result=[]
yield word
else:
result.append(word)
if result:
yield ' '.join(result)
def format_messages(messages):
title='TEXT1'
num=1
for message in messages:
if message in KEYWORD_LIST:
title='TEXT1'
elif message in KEYWORD_LIST1:
title='NEWTEXT'
for line in textwrap.wrap(message,width=65):
yield 'DATA|{n}|{t}|{l}'.format(n=num,t=title,l=line)
num+=1
TEXT='''STUFF: some random text THINGS: some random text and some more random text and stuff JUNK: crazy randomness CRAP: such random stuff I cant believe how random'''
for line in format_messages(text_to_message(TEXT)):
print(line)