New line being printed as "\n" instead of actual new line - python

I'm trying to print a simple game board.
places = [" "] * 9
board = (places[8] + "|" + places[7] + "|" + places[6] + "\n",
places[5] + "|" + places[4] + "|" + places[3] + "\n",
places[2] + "|" + places[1] + "|" + places[0] + "\n")
print(board)
But instead of a board I get this:
(' | | \n', ' | | \n', ' | | \n')
I want to print it without the parentheses and with new lines instead of \n. How can I do this?

Don't print whole tuple, but it's elements, e.g.:
for i in board:
print(i)

You just have to use this line to print:
print(*board,sep="")
Explanation: the operator * is the unpacking operator: the tuple board is then unpacked, and it is like you've done:
print( places[8] + "|" + places[7] + "|" + places[6] + "\n",
places[5] + "|" + places[4] + "|" + places[3] + "\n",
places[2] + "|" + places[1] + "|" + places[0] + "\n",
sep="")

Because you've put commas on the end of each line in the brackets, you've made a tuple, which is an iterable, like a list. Just replace the commas with a + at the start of the next line
board = ('line 1' + '\n'
+ 'line 2' + '\n'
+ 'line 3' + '\n')
This creates a string instead of a tuple.

places = [" "] * 9
print(places[8] + "|" + places[7] + "|" + places[6] + "\n" + places[5] + "|" +
places[4] + "|" + places[3] + "\n" + places[2] + "|" + places[1] + "|" + places[0] +
"\n")
This is what you're looking for.
The problem was that "\n" only works in print statements.

Related

Is there a way to solve this TypeError [duplicate]

This question already has answers here:
Why do I get an IndexError (or TypeError, or just wrong results) from "ar[i]" inside "for i in ar"?
(4 answers)
Closed 6 months ago.
I am having trouble figuring out what is wrong with my code. I need help.
next(fhr) # skip header row
customer_list = [] # initialize empty customer list
for line in fhr:
ls = line.split(',')
customer_list.append([ls[0], ls[1], ls[2], ls[3], ls[4], ls[5], ls[6], int(ls[7]), ls[8], ls[9], ls[10].strip('\n')])
from operator import itemgetter
customer_list.sort(key=itemgetter(7), reverse=True)
print(customer_list)
writepath = './loan-data-output-v1.csv'
fwh = open(writepath, 'w', encoding='utf-8')
fwh.write('Name' +','+ 'State' +','+'Age' +','+'Annual Income'+','+ 'Loan Type' +','+' Loan Amount' +','+ 'Length of Loan in Years' +','+ 'Days Delinquent' +','+ 'Interest Rate' +','+ 'Number of Loans Prior' +','+'Years as Customer' + '\n')
for i in customer_list:
if customer_list[i][7] >= 90:
fwh.write(customer_list[i][0] + ',' + customer_list[i][1] + ',' + customer_list[i][2] + ',' + customer_list[i][3] + ',' + customer_list[i][4] + ',' + customer_list[i][5] + ',' + customer_list[i][6] + ',' + customer_list[i][7] + ',' + customer_list[i][8] + ',' + customer_list[i][9] + ','+ customer_list[i][10] + '\n')
fhr.close()
fwh.close()
I am getting this error for the last for loop and I'm not sure what to do about it. Can someone help.
TypeError: list indices must be integers or slices, not list
You are using lists of lists so when you use for i in list_of_list, i itself becomes a list..
for i in customer_list:
if i[7] >= '90':
fwh.write(i[0] + ',' + i[1] + ',' + i[2] + ',' + i[3] + ',' + i[4] + ',' + i[5] + ',' + i[6] + ',' + str(i[7]) + ',' + i[8] + ',' + i[9] + ','+ i[10] + '\n')
fhr.close()
fwh.close()
Alternatively you can use,
for i in range(0,len(customer_list)):
if customer_list[i][7] >= '90':
fwh.write(customer_list[i][0] + ',' + customer_list[i][1] + ',' + customer_list[i][2] + ',' + customer_list[i][3] + ',' + customer_list[i][4] + ',' + customer_list[i][5] + ',' + customer_list[i][6] + ',' + str(customer_list[i][7]) + ',' + customer_list[i][8] + ',' + customer_list[i][9] + ','+ customer_list[i][10] + '\n')
fhr.close()
fwh.close()
EDIT: Second method assumes that your length of customer_list is constant or in other words you are not adding anything to customer_list during the loop. Thanks to DanielRoseman for pointing out potential bug in second code..
EDIT 2:
Thanks to quamrana for suggesting this way,
for i in customer_list:
if i[7] >= '90':
i[7] = str(i[7])
fwh.write(','.join(i[0:11]) + '\n')
fhr.close()
fwh.close()

How to get new line

How can I print a new line on the output file? When I try to add the new line with "/n" it just prints /n
This is what I have so far.
``
inputFile = open("demofile1.txt", "r")
outFile = open("Ji
string = line.split(',')
go =(string)[3::]
bo = [float(i) for i in go]
total = sum(bo)
pine = ("%8.2f"%total)
name = string[2] + "," + " " + string[1]
kale = (string[0] + " " + name + " " + "/n")
se)
Current Result
8
53 Baul
A999999
You need to use \n, not /n. So this line:
kale = (string[0] + " " + name + " " + "/n")
Should be:
kale = (string[0] + " " + name + " " + "\n")
Also, please do consider using a str formatter, so all these lines:
go =(string)[3::]
bo = [float(i) for i in go]
total = sum(bo)
pine = ("%8.2f"%total)
name = string[2] + "," + " " + string[1]
kale = (string[0] + " " + name + " " + "/n")
str1 = ''.join(kale)
str2 = ''.join(pine)
outFile.write(str1 + " " + str2 + " ")
Will become:
outFile.write("{} {} {:8.2f}\n".format(string[0], string[2] + ", " + string[1], sum(bo))

Python : Calculate values and send in email

UPDATE : I have corrected my code and below is working fine as expected
Basically i need an output like below in mail.
I achieved this. but need to know if any efficient code then below one.
name 5001 5010 9000 4 %
name 5002 5010 9000 4 %
name 5003 5010 9000 4 %
name 5004 5010 9000 4 %
Storing the values in list.
Below are dummy values
container = []
for server in range(1,5):
container.append('name')
container.append(server + 5000)
container.append(5000+10)
container.append(4000+5000)
container.append(2500 % 12)
print('\n' + str(container))
Assign list of values to msgBody in order to send it via email
I'm just putting piece of code here. Below also working fine
msgBody1 = ''
for count in range(4):
if count == 0:
tempValue = '\n' + '\n' + str(container[count]) + '\t' + str(container[count+1]) + '\t' + str(container[count+2]) + '\t'
+ str(container[count+3]) + '\t' + str(container[count+4])
msgBody1 = msgBody1 + str(tempValue) + ' %'
elif count == 1:
tempValue = '\n' + '\n' + str(container[count+4]) + '\t' + str(container[count+5]) + '\t' + str(container[count+6]) + '\t'
+ str(container[count+7]) + '\t' + str(container[count+8])
msgBody1 = msgBody1 + str(tempValue) + ' %'
elif count == 2:
tempValue = '\n' + '\n' + str(container[count+8]) + '\t' + str(container[count+9]) + '\t' + str(container[count+10]) + '\t'
+ str(container[count+11]) + '\t' + str(container[count+12])
msgBody1 = msgBody1 + str(tempValue) + ' %'
elif count == 3:
tempValue = '\n' + '\n' + str(container[count+12]) + '\t' + str(container[count+13]) + '\t' + str(container[count+14]) + '\t'
+ str(container[count+15]) + '\t' + str(container[count+16])
msgBody1 = msgBody1 + str(tempValue) + ' %'
Any other better and short code to replace msgBody1
Thanks in advance
Your question is not clear; the code example does not make any sense. But from the structure of it, it seems like you are trying to use dict, but you are defining or sourcing lists.
Not sure why for server in servers, I hope your servers list is collection of numerical value, which does not make any sense.
Please go through list Vs dict, and list.append() and how to add new key, value pairs to dictionary.

Not able to wrap lines in Python

else:
fullName = curLineFin[1] + ' ' + curLineFin[2]
players[fullName] = curLineFin[0] + '\t' + curLineFin[1] + \
'\t' + curLineFin[2] + '\t' + curLineFin[3] + '\t' + \
curLineFin[4] + '\t' + curLineFin[5] + '\t' + curLineFin[6] + \
'\t' + curLineFin[7] + '\t' + curLineFin[8] + '\t' + \
curLineFin[9] + '\t' + curLineFin[10] + '\t'
Every time I run the script, I get the error:
players[fullName] = curLineFin[0] + '\t' + curLineFin[1] + \
^
IndentationError: unindent does not match any outer indentation level
Wrap your code with parentheses
players[fullName] = (curLineFin[0] + '\t' + curLineFin[1] +
'\t' + curLineFin[2] + '\t' + curLineFin[3] + '\t' +
curLineFin[4] + '\t' + curLineFin[5] + '\t' + curLineFin[6] +
'\t' + curLineFin[7] + '\t' + curLineFin[8] + '\t' +
curLineFin[9] + '\t' + curLineFin[10] + '\t' )
or
players[fullName] = '\t'.join(curLineFin[:11]) + '\t'
or if this trailing tab char is not needed and you have exactly eleven elements in curLineFin.
players[fullName] = '\t'.join(curLineFin)
Just use parenthesis:
fullName = (curLineFin[1] + ' ' + curLineFin[2] +
players[fullName] = curLineFin[0] + '\t' + curLineFin[1] +
'\t' + curLineFin[2] + '\t' + curLineFin[3] + '\t' +
curLineFin[4] + '\t' + curLineFin[5] + '\t' + curLineFin[6] +
'\t' + curLineFin[7] + '\t' + curLineFin[8] + '\t' +
curLineFin[9] + '\t' + curLineFin[10] + '\t')
The code you have posted does not generate that error, so it's impossible to diagnose exactly what's happening in the different code you're actually running.
The most likely cause is that it's completely unrelated to the backslashes, and you're doing something like mixing tabs and spaces. (The fact that you're using a weird 6-character indent for the block isn't a good sign…)
Another possibility is that you're putting extra spaces after one of the backslashes. This should usually give you a SyntaxError: unexpected character after line continuation character, but it's possible to confuse Python to the point where that passes and you get the following generic SyntaxError for a + with no right operand or IndentationError for the next line.

invalid syntax: None, line 4, pos 72

I can't make a space between year and hour, and I am not allowed to use ",". I have use concatenation.
from datetime import datetime
now = datetime.now()
print str(now.month) + "/" + str(now.day) + "/" + str(now.year), "+ "str(now.hour) + ":" + str(now.minute) + ":" + str(now.second)
Try avoiding such long statements and try format them in a readable way. You have wrongly put the + operator within "" and I believe the , should be printed as a separator between month/day/year and hour:minute:second
print str(now.month) + "/" +
str(now.day) + "/" +
str(now.year) + " " +
str(now.hour) + ":" +
str(now.minute) + ":" +
str(now.second)
+ str(now.year), "+ "str(now.hour) + ":"
Your + is in quotes and you have a comma after str(now.year)
now.strftime('%m/%d/%Y + %H:%M:%S')
type this command after 'now = datetime.now()' and you will get the output you want.

Categories

Resources