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.
Related
I am trying to write a short python function to break a long one_line string into a multi_line string by inserting \n. the code works fine when i simply insert \n into the string but i get an index out of range error when i insert a conditional check to add hyphenation as well. Here is the code that i have written.
Sentence = "Python string comparison is performed using the characters in both strings. The characters in both strings are compared one by one. When different characters are found then their Unicode value is compared. The character with lower Unicode value is considered to be smaller."
for i in range(1, int(len(Sentence)/40)+1):
x = i*40
Sentence = Sentence[:x] + "\n" if Sentence[x] == " " else "-\n" + Sentence[x:]
print(Sentence)
Here is the error message i get.
Traceback (most recent call last):
File "/media/u1/data/prop.py", line 4, in <module>
Sentence = Sentence[:x] + "\n" if Sentence[x] == " " else "-\n" + Sentence[x:]
IndexError: string index out of range
The conditional expression is greedy, parsed as if you had written
Sentence = Sentence[:x] + \
("\n" if Sentence[x] == " " else "-\n" + Sentence[x:])
As a result, you are doing one of two operations:
Sentence[:x] + '\n' if you find a space
Sentence[:x] + "-\n" + Sentence[x:] if you find a different character.
Note that case 1 shortens your sentence incorrectly, but your range object is based on the original correct list.
The solution is to use parentheses to define the conditional expression correctly:
for i in range(1, int(len(Sentence)/40)+1):
x = i*40
c = Sentence[x]
Sentence = Sentence[:x] + (f"\n" if c == " " else f"{c}-\n") + Sentence[x+1:]
# ^ ^
Well the issue might not be obvious in the start but when you start looking at the if statement in the middle of string concatenation, you will understand. For a minute just focus on the following line:
Sentence = Sentence[:x] + "\n" if Sentence[x] == " " else "-\n" + Sentence[x:]
Python would parse this statement like so:
Sentence = (Sentence[:x] + "\n") if Sentence[x] == " " else ("-\n" + Sentence[x:])
Notice the brackets carefully. This is exactly the reason why the length of the string held by the variable Sentence is decreasing after each iteration which triggers the IndexError exception. Hence, in order to address this issue, we will have to explicitly tell Python what we are expecting. So, it could be written as such:
Sentence = Sentence[:x] + ("\n" if Sentence[x] == " " else "-\n") + Sentence[x:]
string = "Python string comparison is performed using the characters in both strings. The characters in both strings are compared one by one. When different characters are found then their Unicode value is compared. The character with lower Unicode value is considered to be smaller."
stc = ""
for j in range(1 + len(string) // 40):
stc += string[j * 40:40 * (j + 1)] + "\n"
print(stc)
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.
I have a text file that I am reading in, and based on certain conditions modifying specific lines and rewriting the file to a new text file. My present code mostly works but one of the elif statements seems to be simply ignored by Python as there are no run time errors. A MWE is as follows:
energy = .1
source = str('source x y z energy=%f' %energy)
c = energy - 0.001
c_string = str("1010 %f %f" %(c, energy))
f = open("file.txt", "r+")
with open ("newfiletxti", 'w') as n:
d = f.readlines()
for line in d:
if not line.startswith("source"):
if not line.startswith("xyz"):
n.write(line)
elif line.startswith("source"):
n.write(source + "\n")
elif line.startswith("xyz"):
n.write(c_string + "\n")
n.truncate()
n.close()
The code:
elif line.startswith("source"):
n.write(source + "\n")
Works as expected where the line in the text file is replaced with the string titled "source" however the next block:
elif line.startswith("xyz"):
n.write(c_string + "\n")
Has no effect. The new text file is simply missing the line that starts with xyz. My guess is my syntax for multiple elif statements is incorrect but I am uncertain as to why.
The first if and elif handle all the cases -- either the line starts with source or it doesn't. I think you need to combine the first if and its nested if into a single condition:
if not line.startswith("source") and not line.startswith("xyz"):
n.write(line)
or the equvivalent (by de Morgan's Laws):
if not(line.startswith("source") or line.startswith("xyz")):
n.write(line)
Or you can make it clearer by reordering your conditions:
if line.startswith("source"):
n.write(source + "\n")
elif line.startswith("xyz"):
n.write(c_string + "\n")
else:
n.write(line)
Try your if block like this:
if line.startswith("source"):
n.write(source + "\n")
elif line.startswith("xyz"):
n.write(c_string + "\n")
else:
n.write(line)
The third elif will never be reached. Here is the code reduced for clarity:
if not line.startswith("source"):
# suff
elif line.startswith("xyz"):
# stuff
Something that starts with "xyz" does not start with "source".
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?).
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