Annoying spaces that won't disappear. What should I do? - python

I am currently making a game with Python.
I want the code to read:
[00:00:00] Name|Hello!
Here is my code:
print(Fore.YELLOW + Style.BRIGHT + '['),
print strftime("%H:%M:%S"),
print ']',
print(Style.BRIGHT + Fore.RED + ' Name'),
print(Fore.BLACK + '|'),
print(Fore.WHITE + Style.DIM + 'Hello!')
time.sleep(5)
Instead - for some reason - it becomes like this:
[ 00:00:00 ] Name | Hello!
I have no idea what's wrong with this code, or how to fix it.
I would really appreciate all the help I can get! Thank you.

Printing with a single print statement and a comma always prints a trailing space.
Either use one print statement with everything concatenated, or use sys.stdout.write() to write to the terminal directly without the extra spaces:
print Fore.YELLOW + Style.BRIGHT + '[' + strftime("%H:%M:%S") + ']',
or
sys.stdout.write(Fore.YELLOW + Style.BRIGHT + '[')
sys.stdout.write(strftime("%H:%M:%S"))
sys.stdout.write(']')
or use string formatting:
print '{Fore.YELLOW}{Style.BRIGHT}[{time}] {Style.BRIGHT}{Fore.RED} Name {Fore.BLACK}| {Fore.WHITE}{Style.DIM}Hello!'.format(
Style=Style, Fore=Fore, time=strftime("%H:%M:%S"))

Another option is to use the end="" option to print(). This prints no linefeed and also does not add the extra space at the end.
print(Style.BRIGHT + Fore.RED + ' Name', end="")
print(Fore.BLACK + '|', end="")
print(Fore.WHITE + Style.DIM + 'Hello!')
The caveat being that the end option is only available with Python 3. It's also available in Python 2.6-ish if you from __future__ import print_function

Related

what is the purpose of return_string = " " in the code below. Additionally what is happening in line 4 when " " is added to str(x)

def even_numbers(maximum):
return_string = " "
for x in range(2, maximum+1, 2):
return_string += str(x) + " "
return return_string.strip()
Hi i recently started learning how to code and i dont understand equating empty quotation marks and in some codes adding empty quotation marks to strings like in line 4
It's not empty, it's a space.
Let's say you add the following words:
"hello" "friend"
Without the spaces it would become "hellofriend".
With the spaces it would be "hello friend".

How to make last element of list finish with a dot and the others with a comma?

I made this list with a for loop that points errors when yoy choose a name. I'd like to know how can I make it so that the last line finishes with '.' and the others finish with ';'.
while True:
if len(errors_list) != 0:
print("Your name has thesse errors::")
for i in errors_list:
print(" " + str(errors_list.index(i) + 1) + "- " + i + ".")
print("Try again.")
errors_list.clear()
name = input("My name is ").title()
choose_name(name)
else:
print("Nice to meet you, " + fname + " " + sname + ".")
break
Result when I type a name like '--- ':
Your name has these errors:
1- It has no letters.
2- It has symbols.
3- The last letter is a space.
Try again.
My name is
I'd like to make it so that 1 and 2 finish with ';' and 3 with '.'. Thanks!
All the existing solutions so far seem pretty poor, this is as print is expensive to call.
errors_list.index(i) runs in O(n) time making your solution run in O(n^2) time. You can improve this, to O(n) time, by using enumerate.
You can also think of what you're doing simply as concatenating values of a list and adding a period.
I would use:
errors = [f' {i}- {error}' for i, error in enumerate(errors_list, 1)]
print(';\n'.join(errors) + '.')
Extending Roman Perekhrest's answer, enumerate has an optional parameter start:
errors_list = ['It has no letters', 'It has symbols', 'The last letter is a space']
for i, err in enumerate(errors_list, start=1):
print("\t{}- {}{}".format(i, err, ';' if i < len(errors_list) else '.'))
additionaly with Python 3.6+ you can use f-strings instead of format:
errors_list = ['It has no letters', 'It has symbols', 'The last letter is a space']
for i, err in enumerate(errors_list, start=1):
print(f"\t{i}- {err}{';' if i < len(errors_list) else '.'}")
Instead of:
for i in errors_list:
print(" " + str(errors_list.index(i) + 1) + "- " + i + ".")
do
s = len(errors_list)
for e, i in enumerate(errors_list):
ending = ";" if e + 1 < s else "."
print(" " + str(errors_list.index(i) + 1) + "- " + i + ending)
EDIT:
to those jumping to the gun - OP did write in a title comma, but he used semicolon (;) twice (!) in a question itself.
Simply with enumerate function:
errors_list = ['It has no letters', 'It has symbols', 'The last letter is a space']
...
for i, err in enumerate(errors_list):
print(" {}- {}{}".format(i+1, err, ';' if i+1 != len(errors_list) else '.'))
The crucial loop will output:
1- It has no letters;
2- It has symbols;
3- The last letter is a space.

What does '+ +' mean in python?

I'm reading a python book. It's explaining for loops and range() function.
But I don't understand what does '+ and +' mean.
for i in range(7):
print('hello('+str(i)+')')
Actually it should read as:
string_a + string_b + string_c
It is not about "+ xxx +".
It literally concatenate string_a, string_b and string_c together albeit it is not pythonic.
A more pythonic way may be:
print( "hello({my_var})".format(my_var=i) )

One line output for two 'print' lines

I'm new to programming and I have a question as if there's a way to get one line output for two 'print' lines.
Ex:
end1 = ("A")
end2 = ("B")
end3 = ("C")
end4 = ("D")
print (end1 + end2,)
print (end3 + end4)
Response currently is
AB
CD
Is there a way to get response in one line with two 'print' input lines?
AB CD
default end value is \n , You can define your own end
Try this
print (end1 + end2,end="")
print (end3 + end4,end="")
print(end1 + end2 + ' ' + end3 + end4)
OR
print('{:s}{:s} {:s}{:s}'.format('A','B','C','D'))
OR
print(end1 + end2, end=" ")
print(end3 + end4)
If you don't want the last line to output a newline, you can add end="" to it. In general, the default end argument of print is \n but you can change it to whatever you want.

Python unexpected EOF while parsing : syntax error

I am trying to do a simple toto history with a dictionary and function however I have this funny syntax error that keeps appearing that states "unexpected EOF while parsing" on the python shell when I try to runs it. I re-looked over and over however I cannot find the error. I used input for input of integers therefore I do not think that the problem might lie with the input or raw_input. Please help me ! Below are my codes and the error on the python shell.
options()
choice = input ("Enter your choice: ")
print
while choice != -1:
if choice == 1:
print("Choice 1")
for key in toto_book:
print key + "\t" + "Day: " + toto_book[key][0] + '\t' + 'Winning Numbers: ' + str(toto_book[key][1] + 'Additional Number: ' + toto_book[key][2]
elif choice == 2:
print("Choice 2")
draw = raw_input("Enter draw date(dd/mm/yy): ")
if draw in toto_book:
print (draw + "\t" + "Day: " + toto_book[draw][0] + "\t" + "Winning Numbers: " + str(toto_book[draw][1]) + 'Additional Number: ' + toto_book[draw][2])
else:
print draw + ' cannot be found.'
There is a syntax error at the elif choice == 2: line.
Updated
As pointed out by #cricket_007, this answer is based on the false assumption that Python 3 is being used. Actually, Python 2 is being used and the only serious problem is that the call to str is missing a closing parenthesis.
You are using Python 3 in which print is a function, not a statement (as it is in Python 2).
This is the line causing the problem:
print key + "\t" + "Day: " + toto_book[key][0] + '\t' + 'Winning Numbers: ' + str(toto_book[key][1] + 'Additional Number: ' + toto_book[key][2]
Add parentheses to make print a function call, i.e. print(...):
print(key + "\t" + "Day: " + toto_book[key][0] + '\t' + 'Winning Numbers: ' + str(toto_book[key][1]) + 'Additional Number: ' + toto_book[key][2])
Also, the call to str() was missing the closing parenthesis.
There is a similar problem on line 15.
Other problems:
input() returns a string, not an integer so your if choice ==
statements will never be true. Either convert choice to an integer
with choice = int(choice) after the input(), or use a string in
the if statements, e.g. if choice == '1'.
The while loop is infinte, and unnecessary for the code shown (perhaps it is a work in progress?).

Categories