I am trying to make a text game, that will start off with a timer that will add 1 letter to form a string every 0.05 seconds, so it looks like someone is typing a sentence.
Ex. "Hello, this is a test" would start off with h then e then l then l then o, with a time period between the letters being printed on the line.
import time
string = "Hello, this is a test"
count=1
while count >0:
time.sleep(0.05)
print(string[:1]),
That is the code i tried, but i'm just lost and have no idea how to continue. Any ideas on how i can make this work?
Replace your while loop with a for loop iterating over the string you want to print. That'll give you each letter in turn and stop your loop at the end. I also recommend placing this behaviour in a function like so:
def typeText(text, delay=0.05):
for character in text:
print character,
time.sleep(delay)
typeText("Hello, this is a text")
To solve the problem of the spaces, you then have 3 options, in order from most to least side effects:
Switch to python3 which uses print as a function with an end argument that you can set to the empty string;
from __future__ import print_function which will give you the same print function without all the other caveats from python3;
replace print by sys.stdout.write(). This function is what print wraps around by default
This is the way to do it,
EDIT: Since OP does not want spaces after printing each character,so i set end=''
import time
string = "Hello, this is a test"
count=0
while count<len(string):
time.sleep(0.05)
print (string[count],end='')
count = count+1
try something like this:
import time
string = "Hello, this is a test"
count=1
for i in string:
time.sleep(0.05)
print(i)
Your code doesn't work (as you want it to work) because you have an infinite loop there.
You could write like this (just like improvement of your existing code):
import time
string = "Hello, this is a test"
count = len(string)
while count > 0:
time.sleep(0.05)
print(string[:1]),
count -=1
But this is not Pythonic.
The only right way to do it here is to code it like this:
import time
string = "Hello, this is a test"
for letter in string:
time.sleep(0.05)
print letter
And this is not Pythonic too:
for i in range(len(string)):
# Do something...
You probably want to replace the 'while' with something like
for i in range(len(string)):
That'll iterate through the string.
Related
I already turned in this assignment but it is driving me crazy. We were given a method to strip punctuation from a dictionary using a "for" loop with this example:
import string
quote = " The joy of coding Python should be in seeing short, concise, readable classes that express " \
"a lot of action in a small amount of clear code -- not in reams of trivial code that bores the " \
"reader to death. "
print(quote)
word_list = quote.split()
for word in word_list:
word = word.strip(string.punctuation)
print(word)
Our assignment for the week was to take the Gettysburg address saved as a .txt file and create a dictionary that has a count of how many times all the words appear. My first try I did this:
import string
def word_counter(speech, word_dictionary):
for word in speech:
if word in word_dictionary:
word_dictionary[word] += 1
else:
word_dictionary[word] = 1
def process_line(word_list, word_dictionary):
##split speech into list of words
words_split = word_list.split()
##remove puncation from list
for word in words_split:
word = word.strip(string.punctuation)
else:
word_counter(word, word_dictionary)
# Printing extra Values
pretty_print(word_dictionary)
def pretty_print(word_dictionary):\
##clean up values that shouldn't be there
##word_dictionary.pop("")
##word_dictionary.pop("19")
##word_dictionary.pop("1863")
##word_dictionary.pop("Abraham")
##word_dictionary.pop("Lincoln")
##Calculating how many words are in the dictionary
word_count_sum = len(word_dictionary.items())
print("Length of dictionary: ", word_count_sum)
for key, value in sorted(word_dictionary.items(), key=lambda kv: kv[1], reverse=True):
print("%s: %s" % (key, value))
def main():
##creating empty dictionary
word_count_dict = {}
##uploading file
gba_file = open('gettysburg.txt','r')
data = gba_file.read()
process_line(data,word_count_dict)
if __name__ == '__main__':
main()
What happens with this is the only entries in the dictionary are 1,9,8,3. I did a print statement and it is running through the entire loop. It also is looping through the entire list when after the split. I was able to complete the assignment by using:
for word in words_split:
for character in word:
if character in string.punctuation:
word = word.replace(character,"")
input_list.append(word)
but I am trying to learn so I want to know what I was doing wrong. Can anyone help? Sorry for the lengthy post and let me know if you need the .txt file to solve this.
You have an errant else in here that's messing up your for loop:
for word in words_split:
word = word.strip(string.punctuation)
else:
word_counter(word, word_dictionary)
The else: clause executes only once (or never) after the for loop is completely done (unless there's a break), so you're only calling word_counter on the very last word from the loop. You don't need the else: here at all; just delete that line, and word_counter will be called once per word.
Note that Python comes with a built-in class, collections.Counter, that will do this exact thing without you having to write your own function.
import string
quote = " The joy of coding Python should be in seeing short, concise, readable classes that express " \
"a lot of action in a small amount of clear code -- not in reams of trivial code that bores the " \
"reader to death. "
for s_char in string.punctuation:
quote = quote.replace(s_char,"")
The function .replace() replaces all characters in the string, not only one
Whenever i try to split the str in my code with str.split and time.sleep the output comes as the word + none
I want this string to split and print the word every 0.3sec . I am really confused bcoz i am beginner.
import time
lyrics_str=('''class is starting today''')
for word in lyrics_str.split():
print('''
''' ,word ,time.sleep(0.3) )
The out come is this
class None
is None
starting None
today None
You are printing the output of the sleep function which (unsurprisingly perhaps) doesn't return anything!
What your really want to do is print and then sleep:
import time
lyrics_str = "class is starting today"
for word in lyrics_str.split():
print(word)
time.sleep(0.3)
I have been trying to write the code for this program for a while now, but I just cannot figure it out. I am very confused. I would appreciate the help:
Write a function that takes two strings. The second string should only be one character long. The function should return how many times the second string occurs in the first string.
You will need:
A function declaration, with parameters.
A for loop.
An if statement.
A return statement.
What I have so far:
string_one = "I love coding!"
string_two = "I"
if string_two in string_one: print "Hi"
Considering the code you have provided, it indeed works if string_two is in string_one, meaning that your if-condition is correct. However, it will only run once, so if string_two occurs multiple times in string_one, it will ignore all other occurences and print Hi only once. As a result, you need to add your if-condition into a for-loop to catch all occurences of string_two in string_one.
string_one = "I love coding!"
string_two = "o" # changed to 'o' since it has more than 1 occurence in string_one
for letter in string_one: # look at each letter in string_one, one after another
if string_two in letter: # also possible: if string_two == letter
print "Hi" # print Hi when the letter is found
All that's left to do now according to your task is to wrap this code into a function with two parameters (ideally one parameter called sentence and another one called character or similar) and return something. However, I will leave figuring this out to yourself, good luck! :)
First off, let's note that this problem could be solved using str.count(thing_to_count). That's what you should use in general, but I see here you are probably asking for help on an assignement (generally discouraged on Stack Overflow, but I personally don't have an issue with it). Anyway, here's the code I made for this.
def count_in_string (sentence, thing_to_count):
times = 0
for word in sentence:
for letter in word:
if letter == thing_to_count: times += 1
return times
So:
Declare count_in_string as a function with the arguments sentence and thing_to_count.
Set times to be the amount of times thing_to_count_ appears in sentence (so far 0).
Loop through every word, and then letter in the sentence.
See if the letter is the thing_to_count, and if so add 1 to times.
Return times as the result.
I'm a beginner, how can I do ghost-like typist in console?
EDIT:
I did something like this, just prints a letter per line:
def ghostPrint(sentence):
for letter in sentence:
time.sleep(0.12)
print (letter)
ghostPrint("Hello world...")
This one, just changes letter in the same line:
def ghostPrint(sentence):
for letter in sentence:
time.sleep(0.12)
print (letter, end="\r")
ghostPrint("Hello world...")
And this one, prints Hello World... then closes:
def ghostPrint(sentence):
for letter in sentence:
time.sleep(0.12)
print (letter, end = " ")
ghostPrint("Hello world...")
I am currently using Python 3.5.
In Python 2, a trailing comma after a print statement will suppress the newline (it also adds a space between the arguments to print). So
print var1, var2,
prints the values of var1 and var2 with a space in between, and does not print a trailing newline.
In Python 3, the print function takes two arguments, sep and end. The default values are sep=' ' and end='\n'. Use sep to change what string is used to separate arguments to print, and use end to change what string is printed after everything else.
Use a trailing comma(,) to avoid a newline.
import time
def ghostPrint(sentence):
for letter in sentence:
time.sleep(0.12)
print (letter),
ghostPrint("Hello world...")
In python 3.x using print (letter,end='') will not work I guesses as it print every thing at once.
I'm writing a function that will take a word as a parameter and will look at each character and if there is a number in the word, it will return the word
This is my string that I will iterate through
'Let us look at pg11.'
and I want to look at each character in each word and if there is a digit in the word, I want to return the word just the way it is.
import string
def containsDigit(word):
for ch in word:
if ch == string.digits
return word
if any(ch.isdigit() for ch in word):
print word, 'contains a digit'
To make your code work use the in keyword (which will check if an item is in a sequence), add a colon after your if statement, and indent your return statement.
import string
def containsDigit(word):
for ch in word:
if ch in string.digits:
return word
Why not use Regex?
>>> import re
>>> word = "super1"
>>> if re.search("\d", word):
... print("y")
...
y
>>>
So, in your function, just do:
import re
def containsDigit(word):
if re.search("\d", word):
return word
print(containsDigit("super1"))
output:
'super1'
You are missing a colon:
for ch in word:
if ch.isdigit(): #<-- you are missing this colon
print "%s contains a digit" % word
return word
Often when you want to know if "something" contains "something_else" sets may be usefull.
digits = set('0123456789')
def containsDigit(word):
if set(word) & digits:
return word
print containsDigit('hello')
If you desperately want to use the string module. Here is the code:
import string
def search(raw_string):
for raw_array in string.digits:
for listed_digits in raw_array:
if listed_digits in raw_string:
return True
return False
If I run it in the shell here I get the wanted resuts. (True if contains. False if not)
>>> search("Give me 2 eggs")
True
>>> search("Sorry, I don't have any eggs.")
False
Code Break Down
This is how the code works
The string.digits is a string. If we loop through that string we get a list of the parent string broke down into pieces. Then we get a list containing every character in a string with'n a list. So, we have every single characters in the string! Now we loop over it again! Producing strings which we can see if the string given contains a digit because every single line of code inside the loop takes a step, changing the string we looped through. So, that means ever single line in the loop gets executed every time the variable changes. So, when we get to; for example 5. It agains execute the code but the variable in the loop is now changed to 5. It runs it agin and again and again until it finally got to the end of the string.