syntax error with .format() (Python 3.2.3) - python

So I am trying to write a program that writes a word, fills 20 spaces with markup(< or >), then writes that same word backwards. It also takes user input.
Can anyone tell me what im doing wrong
while test2 == 1 :
test = input("Enter a word to format. Entering QUIT will exit the program:")
if test == ("quit"):
print("You have quit the program.")
break
else:
print("{0:*<20}{1:*>20})".format(
"test")(["test"::-1])

Syntactically you have a " in the wrong place in your last print statement.
print("{0:*<20}{1:*>20}").format("test")(["test"::-1])
^
You also some other syntax errors with your format() arguments, this will work for the literal string "test" but you'll need to replace it with a variable to use it with actual user input:
print("{0:*<20}{1:*>20}").format("test","test"[::-1])

Your last line has errors, try the follwing to get 20 spaces between the words
In [1]: s = "test"
In [2]: print('{0:<20}{1}'.format(s,s[::-1]))
test tset
You can also use print('{0}{1}{2}'.format(s," "*20,s[::-1])) which is subjectively cleaner.

Related

python 3 input without newline

I am new to coding. And I would like to know if there's a way for input function to not print newline character after the value is entered. Something like print function's argument end. Is there any way?
Well, you can't make input() trigger by anything besides 'Enter' hit (other way may be using sys.stdin and retrieving character one-by-one until you receive some stop marker, but it's difficult both for programmer and for user, I suppose). As a workaround I can the suggest the following: if you can know the length of line written before + length of user input, then you can use some system codes to move cursor back to the end of previous line, discarding the printed newline:
print("This is first line.")
prompt = "Enter second: "
ans = input(prompt)
print(f"\033[A\033[{len(prompt)+len(ans)}C And the third.")
\033[A moves cursor one line up and \033[<N>C moves cursor N symbols right. The example code produces the following output:
This is first line.
Enter second: USER INPUT HERE And the third.
Also note that the newline character is not printed by your program, it's entered by user.
name=input('Enter your name : ')
print('hello',name,end='')
I know about the end function which is abov

Function is not being called after input assigns a value (Python)

I have a small file with a bunch of phrases on each line. I want the user to type a number and that number will print the selected line.
def printSpecLine(x):
print('started')
with open('c:/lab/save.txt') as f:
for i, line in enumerate(f, 1):
if i == x:
break
print (line)
print('done')
f.close()
s = int(input("Enter a number: "))
printSpecLine(s)
I've ran this with no errors, but the function isn't being called at all. Printing "started" (second line) didn't even occur. Am I missing a step here?
The only explanation for this is that you are not actually inputting to the prompt! There doesn't seem to be any other reason why at least the first print wouldn't be made.
Remember that input() is blocking, so until you enter your number and press enter, the program will be halted where it is (i.e. not call the function).
Apparently the ide i was using has a problem with raw input and integers being converted. Sublime Text 3 doesn't take python input very well. Thank you for your answer.

sys.stdin in for loop is not grabbing user input

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 + "!")

Using a if statement condition to see NULL user input and print: "sometext ..."

Python with its indents and no semi-colons and brackets is taking some time for me to get used to ... coming from C++. This, I'm sure is an easy fix, but I can't seem to find the problem. Your help is greatly appreciated. Here is what I have. When I run this code it acts like the second 'if' statement does not exist. Even if I comment out the first 'if' statement, the print line in the second 'if' statement is never printed to screen:
import re
while True:
stringName = raw_input("Convert string to hex & ascii(type stop to quit): ").strip()
if stringName == 'stop':
break
if stringName is None: print "You must enter some text to proceed!"
print "Hex value: ", stringName.encode('hex')
print "ASCII value: ", ', '.join(str(ord(c)) for c in stringName)
The return value of raw_input() is always a string, and never None. If you want to check for an empty string "", you can use
if not string_name:
# whatever
raw_input always returns a string and never None. Check out raw_input help.
raw_input([prompt]) -> string
Read a string from standard input. The trailing newline is stripped.
If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.
On Unix, GNU readline is used if enabled. The prompt string, if given,
is printed without a trailing newline before reading.

Weird program behaviour in Python

When running the following code, which is an easy problem, the Python interpreter works weirdly:
n = input()
for i in range(n):
testcase = raw_input()
#print i
print testcase[2:(int(testcase[0])+1)]+testcase[(int(testcase[0])+2):]
The problem consists in taking n strings and deleting a single character from them.
For example, given the string "4 PYTHON", the program should output "PYTON".
The code runs ok, but if I take out the comment mark, the statement print i makes the interpreter give an unexpected EOF while parsing. Any idea on why this happens?
EDIT: I'm working under Python 2.5, 32 bits in Windows.
Are you sure that the problem is the print i statement? The code works as
expected when I uncomment that statement and run it. However, if I forget to
enter a value for the first input() call, and just enter "4 PYTHON" right off
the bat, then I get:
"SyntaxError: unexpected EOF while parsing"
This happens because input() is not simply storing the text you enter, but also
running eval() on it. And "4 PYTHON" isn't valid python code.
I am yet another who has no trouble with or without the commented print statement. The input function on the first line is no problem as long as I give it something Python can evaluate. So the most likely explanation is that when you are getting that error, you have typed something that isn't a valid Python expression.
Do you always get that error? Can you post a transcript of your interactive session, complete with stack trace?
This worked for me too, give it a try...
n = raw_input()
n = int(n)
for i in range(n):
testcase = raw_input()
print i
print testcase[2:(int(testcase[0])+1)]+testcase[(int(testcase[0])+2):]
Note the n = int(n)
PS: You can continue to use n = input() on the first line; i prefer raw_input.

Categories

Resources