How to do ghost-like typist in Python - python

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.

Related

Printing every other letters of a string without the spaces on Python

I am trying to build a function that will take a string and print every other letter of the string, but it has to be without the spaces.
For example:
def PrintString(string1):
for i in range(0, len(string1)):
if i%2==0:
print(string1[i], sep="")
PrintString('My Name is Sumit')
It shows the output:
M
a
e
i
u
i
But I don't want the spaces. Any help would be appreciated.
Use stepsize string1[::2] to iterate over every 2nd character from string and ignore if it is " "
def PrintString(string1):
print("".join([i for i in string1[::2] if i!=" "]))
PrintString('My Name is Sumit')
Remove all the spaces before you do the loop.
And there's no need to test i%2 in the loop. Use a slice that returns every other character.
def PrintString(string1):
string1 = string1.replace(' ', '')
print(string1[::2])
Replace all the spaces and get every other letter
def PrintString(string1):
return print(string1.replace(" ", "") [::2])
PrintString('My Name is Sumit')
It depends if you want to first remove the spaces and then pick every second letter or take every second letter and print it, unless it is a space:
s = "My name is Summit"
print(s.replace(" ", "")[::2])
print(''.join([ch for ch in s[::2] if ch != " "]))
Prints:
MnmiSmi
Maeiumt
You could alway create a quick function for it where you just simply replace the spaces with an empty string instead.
Example
def remove(string):
return string.replace(" ", "")
There's a lot of different approaches to this problem. This thread explains it pretty well in my opinion: https://www.geeksforgeeks.org/python-remove-spaces-from-a-string/

split strings with multiple special characters into lists without importing anything in python

i need to make a program that will capitalize the first word in a sentence and i want to be sure that all the special characters that are used to end a sentence can be used.
i can not import anything! this is for a class and i just want some examples to do this.
i have tried to use if to look in the list to see if it finds the matching character and do the correct split operatrion...
this is the function i have now... i know its not good at all as it just returns the original string...
def getSplit(userString):
userStringList = []
if "? " in userString:
userStringList=userString.split("? ")
elif "! " in userStringList:
userStringList = userString.split("! ")
elif ". " in userStringList:
userStringList = userString.split(". ")
else:
userStringList = userString
return userStringList
i want to be able to input something like this is a test. this is a test? this is definitely a test!
and get [this is a test.', 'this is a test?', 'this is definitely a test!']
and the this is going to send the list of sentences to another function to make the the first letter capitalized for each sentence.
this is an old homework assignment that i could only make it use one special character to separate the string into a list. buti want to user to be able to put in more then just one kind of sentence...
This may hep. use str.replace to replace special chars with space and the use str.split
Ex:
def getSplit(userString):
return userString.replace("!", " ").replace("?", " ").replace(".", " ").split()
print(map(lambda x:x.capitalize, getSplit("sdfsdf! sdfsdfdf? sdfsfdsf.sdfsdfsd!fdfgdfg?dsfdsfgf")))
Normally, you could use re.split(), but since you cannot import anything, the best option would be just to do a for loop. Here it is:
def getSplit(user_input):
n = len(user_input)
sentences =[]
previdx = 0
for i in range(n - 1):
if(user_input[i:i+2] in ['. ', '! ', '? ']):
sentences.append(user_input[previdx:i+2].capitalize())
previdx = i + 2
sentences.append(user_input[previdx:n].capitalize())
return "".join(sentences)
I would split the string at each white space. Then scan the list for words that contain the special character. If any is present, the next word is capitalised. Join the list back at the end. Of course, this assumes that there are no more than two consecutive spaces between words.
def capitalise(text):
words = text.split()
new_words = [words[0].capitalize()]
i = 1
while i < len(words) - 1:
new_words.append(words[i])
if "." in words[i] or "!" in words[i] or "?" in words[i]:
i += 1
new_words.append(words[i].capitalize())
i += 1
return " ".join(new_words)
If you can use the re module which is available by default in python, this is how you could do it:
import re
a = 'test this. and that, and maybe something else?even without space. or with multiple.\nor line breaks.'
print(re.sub(r'[.!?]\s*\w', lambda x: x.group(0).upper(), a))
Would lead to:
test this. And that, and maybe something else?Even without space. Or with multiple.\nOr line breaks.

Write programs that read a line of input as a string and print every second letter of the string in Python

Write programs that read a line of input as a string and print every second letter of the string in Python?
So far I have written:
string=input('Enter String: ')
for char in range(0,len(string),2):
print(len(char))
if i input a string: qwerty
it should print "qet"
You need to keep it much simpler than this. If you enter a word and are looking to slice it at a specific point, use slicing.
Your criteria: qwerty it should print "qet"
So, you are looking to print every second letter:
>>> a = "querty"
>>> a[::2]
'qet'
Slicing works like this:
[from start: from end: step]
So, in your case, you are looking to simply print every second, so you want to make use of your step. So, simply slice leaving the start and end empty, since you want to position yourself at the beginning of the string and then simply go every second. This is the reasoning behind using [::2]
Every second letter should start with index of 1 not 0. So, if your input is "qwerty", you output should be "wry".
Code below may be able to answer your question.
sentence = input("\nPlease enter a string : ")
print("Every second letter of the string " + sentence + " is ", end="")
for i in range(len(sentence)):
if i % 2 == 1:
print(sentence[i] + " ", end="")

Python text game

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.

How can I suppress the newline after a print statement? [duplicate]

This question already has answers here:
How to print without a newline or space
(26 answers)
How can I print multiple things on the same line, one at a time?
(18 answers)
Closed last month.
I read that to suppress the newline after a print statement you can put a comma after the text. The example here looks like Python 2. How can it be done in Python 3?
For example:
for item in [1,2,3,4]:
print(item, " ")
What needs to change so that it prints them on the same line?
The question asks: "How can it be done in Python 3?"
Use this construct with Python 3.x:
for item in [1,2,3,4]:
print(item, " ", end="")
This will generate:
1 2 3 4
See this Python doc for more information:
Old: print x, # Trailing comma suppresses newline
New: print(x, end=" ") # Appends a space instead of a newline
--
Aside:
in addition, the print() function also offers the sep parameter that lets one specify how individual items to be printed should be separated. E.g.,
In [21]: print('this','is', 'a', 'test') # default single space between items
this is a test
In [22]: print('this','is', 'a', 'test', sep="") # no spaces between items
thisisatest
In [22]: print('this','is', 'a', 'test', sep="--*--") # user specified separation
this--*--is--*--a--*--test
Code for Python 3.6.1
print("This first text and " , end="")
print("second text will be on the same line")
print("Unlike this text which will be on a newline")
Output
>>>
This first text and second text will be on the same line
Unlike this text which will be on a newline
print didn't transition from statement to function until Python 3.0. If you're using older Python then you can suppress the newline with a trailing comma like so:
print "Foo %10s bar" % baz,
Because python 3 print() function allows end="" definition, that satisfies the majority of issues.
In my case, I wanted to PrettyPrint and was frustrated that this module wasn't similarly updated. So i made it do what i wanted:
from pprint import PrettyPrinter
class CommaEndingPrettyPrinter(PrettyPrinter):
def pprint(self, object):
self._format(object, self._stream, 0, 0, {}, 0)
# this is where to tell it what you want instead of the default "\n"
self._stream.write(",\n")
def comma_ending_prettyprint(object, stream=None, indent=1, width=80, depth=None):
"""Pretty-print a Python object to a stream [default is sys.stdout] with a comma at the end."""
printer = CommaEndingPrettyPrinter(
stream=stream, indent=indent, width=width, depth=depth)
printer.pprint(object)
Now, when I do:
comma_ending_prettyprint(row, stream=outfile)
I get what I wanted (substitute what you want -- Your Mileage May Vary)
There's some information on printing without newline here.
In Python 3.x we can use ‘end=’ in the print function. This tells it to end the string with a character of our choosing rather than ending with a newline. For example:
print("My 1st String", end=","); print ("My 2nd String.")
This results in:
My 1st String, My 2nd String.

Categories