so i do not want the results under each other. How can i line it up next to each other? Like 1 1 1 and not 1 under 1 under 1. I did not find any good information about that. I tried print(x,t) but it do not work for for loops or does it?
here
By default, print() appends a newline character to the end of the string.
To have it not do this, simply use the following:
print("Hello World!", end = "")
Related
So I have to take the numbers from a certain file
containing:
1 5
2 300
3 3
9 155
7 73
7 0
Multiply them and add them to a new file
I used the script under here but for some reason, it now gives a syntax error.
f=open('multiply.txt')
f2=open('resulted.txt','w')
while True:
line=f.readline()
if len(line)==0:
break
line=line.strip()
result=line.split(" ")
multiply=int(result[0])*int(result[1])
multiply=str(multiply)
answer=print(result[0],"*",result[1],"=",multiply)
f2.write(str(multiply))
f.close()
f2.close()
i found out that f2.write(multiply) works
but i get all the answers as 1 string (5600913955110)
how do i get it to be 1 good text file and give the right calculation
Update:
f=open('multiply.txt')
f2=open('result.txt','w')
while True:
line=f.readline()
if len(line)==0:
break
line=line.strip()
result=line.split(" ")
multiply=int(result[0])*int(result[1])
multiply=str(multiply)
answer=print(result[0],"*",result[1],"=",multiply)
answer=str(answer)
f2.write(str(answer))
f2.write(str(multiply))
f.close()
f2.close()
output:
None5None600None9None1395None511None0
at the end of the code you have this line:
f2.write(str(answer)
notice there is not a ) at the end and you have two ( in the line.
try this:
f2.write(str(answer))
Also the name of the post sounds like its provoking opinion response. Try to change it so it doesn't mention your friend but the problem at hand.
In most programming languages, there are escape sequences. Escape sequences allow you to do many things. in your case you need to add the escape sequence
"\n"
this will add a new line onto each thing you append to the file.
like this:
answer=str(result[0])+"*"+str(result[1])+"="+str(multiply)
print(answer)
f2.write(str(answer)+"\n")
I do not understand why when inputing a space between the code with \t gives one space of line between the 'green' and 'Some things I learned so far:' output. When I use \n it gives two spaces inbetween. Shouldn't the space be the same for either \t and \n? I know that \t does tab and \n is new line. but I do not understand how \n does two spaces inbetween
Code is:
fav_num = {
'rachel':'blue',
'hannah':'green',
}
print(fav_num['rachel'])
print(fav_num['hannah'])
#6-3
coding_glossary = {
'list':'mutable type where you can store info',
'tuple':'immutable type similar to list',
'string':'simple line of code'
}
print('\t')
print('Some things I learned so far: \n')
print('What a list is:')
print(coding_glossary['list'])
Output is :
blue
green
Some things I learned so far:
What a list is:
mutable type where you can store info
Process finished with exit code 0
python's built-in print function has '\n' as end character implicitly.
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False):
Print objects to the text stream file, separated by sep and followed by end. sep, end, file and flush, if present, must be given as keyword arguments
So, every time you run print() there is a '\n' character that gets printed implicitly unless you override the behavior by passing end= to it. (like end='' for instance)
Your code can be equivalently written:
#
print()
print(‘Some things I learned so far:’)
print()
#
print by default goes to the next line. try
print(" ",end = "")
so you can see '\t' more clearly.
Also, tab jumps to the next block. A block is usually 4 spaces.
Try this and notice where the . is:
print("\t", end=".\n")
print("A\t", end=".\n")
print("ABC\t", end=".\n")
print("ABCD\t", end=".\n")
The statement print('\t') is printing a tab, then returning to the next line, as the default print function automatically adds a newline. So you can't see the tab, but it is there. When you add \n to the end of the string you print, it adds a line return in addition to the default line return.
To remove the default line return, specify the 'end' parameter of the print function:
print('abcd\n', end='')
This will only include one line return.
By default print put a new line at the end, to modify this behavior you can set the end parameter with end=""
Example:
print("this will use 2 lines \n")
print("this will use 1 line")
print("this will use 1 line \n", end="")
Since print() does give an '\n' string at the end of each output the command print('\n') gives the commandline string '\t\n'.
For more details please see the following well documented post Link
"\n" character is a newline character and when you print "\n" it sets the cursor to a new line. print always sets a new line in the end by default. But you can change that behavior by setting the value of end argument to an empty string.
print("hello", end="")
"\t" is a tab character
for i in range(20):
print("current number is\t", I)
# current number is 0
# current number is 1
# current number is 2
# current number is 3
# current number is 4
# current number is 5
# current number is 6
# current number is 7
# current number is 8
# current number is 9
# current number is 10
# current number is 11
# current number is 12
# current number is 13
# current number is 14
# current number is 15
# current number is 16
# current number is 17
# current number is 18
# current number is 19
Find more magic characters which can be useful in your programs
I am trying to make a very simple login script to learn about accessing files and lists but I'm a bit stuck.
newaccno = str(1)
with open("C:\\Python\\Test\\userpasstest.txt","r+") as loginfile:
for line in loginfile.readlines():
line = line.strip()
logininfo = line.split(" ")
print(newaccno in logininfo[0])
while newaccno in logininfo[0]: #issue is here, also tried ==
newaccno += 1
print(newaccno)
loginfile.write(newaccno)
My logic is that it will search logininfo[0] for newaccno and if it is true, increase newaccno by 1 and search again until it is false then write to file (so if the file has 1, 2 and 3 already then newaccno will end up as 4).
Edit: This is how the txt file looks, the first number represents newaccno before it gets split.
1 abc qwe
2 123 456
(adapted from comment)
Your while loop needs to be inside your for loop for it to work. If it is outside logininfo[0] will always be the last line's first character
I'm using Python 3 and I need to parse a line like this
-1 0 1 0 , -1 0 0 1
I want to split this into two lists using Fraction so that I can also parse entries like
1/2 17/12 , 1 0 1 1
My program uses a structure like this
from sys import stdin
...
functions'n'stuff
...
for line in stdin:
and I'm trying to do
for line in stdin:
X = [str(elem) for elem in line.split(" , ")]
num = [Fraction(elem) for elem in X[0].split()]
den = [Fraction(elem) for elem in X[1].split()]
but all I get is a list index out of range error: den = [Fraction(elem) for elem in X[1].split()]
IndexError: list index out of range
I don't get it. I get a string from line. I split that string into two strings at " , " and should get one list X containing two strings. These I split at the whitespace into two separate lists while converting each element into Fraction. What am I missing?
I also tried adding X[-1] = X[-1].strip() to get rid of \n that I get from ending the line.
The problem is that your file has a line without a " , " in it, so the split doesn't return 2 elements.
I'd use split(',') instead, and then use strip to remove the leading and trailing blanks. Note that str(...) is redundant, split already returns strings.
X = [elem.strip() for elem in line.split(",")]
You might also have a blank line at the end of the file, which would still only produce one result for split, so you should have a way to handle that case.
With valid input, your code actually works.
You probably get an invalid line, with too much space or even an empty line or so. So first thing inside the loop, print line. Then you know what's going on, you can see right above the error message what the problematic line was.
Or maybe you're not using stdin right. Write the input lines in a file, make sure you only have valid lines (especially no empty lines). Then feed it into your script:
python myscript.py < test.txt
How about this one:
pairs = [line.split(",") for line in stdin]
num = [fraction(elem[0]) for elem in pairs if len(elem) == 2]
den = [fraction(elem[1]) for elem in pairs if len(elem) == 2]
I am trying to parse a particular text file. I am trying to open the text file and line by line ask if a particular string is there (In the following example case its the presence of the number 01 in the curly brackets), then manipulate a particular string either forwards backwards, or keep it the same. Here's that example, with one line named arbitrarily "go"... (other lines in the full file have similar format but have {01}, {00} etc...
go = 'USC_45774-1111-0 <hkxhk> {10} ; 78'
go = go.replace(go[22:24],go[23:21:-1])
>>> go
'USC_45774-1111-0 <khxkh> {10} ; 78'
I am trying to manipulate the first "hk" (go[22:24]) by replacing it with the same letters but backwards (go[23:21:-1).What I want is to see khxhk but as you can see, the result I am getting is that both are turned backwards to khxkh.
I am also having a problem of executing the specific if statement for each line. Many lines that dont have {01} are being manipulated as if they were....
with open('c:/LG 1A.txt', 'r') as rfp:
with open('C:/output5.txt', 'w') as wfp:
for line in rfp.readlines():
if "{01}" or "{-1}" in line:
line = line.replace(line[25:27],line[26:24:-1])
line = line.replace("<"," ")
line = line.replace(">"," ")
line = line.replace("x"," ")
wfp.write(line)
elif "{10}" or "{1-}" in line:
line = line.replace(line[22:24],line[23:21:-1])
line = line.replace("<"," ")
line = line.replace(">"," ")
line = line.replace("x"," ")
wfp.write(line)
elif "{11}" in line:
line = line.replace(line[22:27],line[26:21:-1])
line = line.replace("<"," ")
line = line.replace(">"," ")
line = line.replace("x"," ")
wfp.write(line)
wfp.close()
Am I missing something simple?
The string replace method does not replace characters by position, it replaces them by what characters they are.
>>> 'apple aardvark'.replace('a', '!')
'!pple !!rdv!rk'
So in your first case, you are telling to replace "hk" with "kh". It doesn't "know" that you want to only replace one of the occurrences; it just knows you want to replace "hk" with "kh", so it replaces all occurrences.
You can use the count argument to replace to specify that you only want to replace the first occurrence:
>>> go = 'USC_45774-1111-0 <hkxhk> {10} ; 78'
... go.replace(go[22:24],go[23:21:-1],1)
'USC_45774-1111-0 <khxhk> {10} ; 78'
Note, though, that this will always replace the first occurrence, not necessarily the occurrence at the position in the string you specified. In this case I guess that's what you want, but it may not work directly for other similar tasks. (That is, there is no way to use this method as-is to replace the second occurrence or the third occurrence; you can only replace the first, or the first two, or the first three, etc. To replace the second or third occurrence you'd need to do a bit more.)
As for the second part of your question, you are misunderstanding what if "{01}" or "{-1}" in line means. It means, in layman's terms, if "{01}" or if "{-1}" in line. Since if "{01}" is always true (i.e., the string "{01}" is not a false value), the whole condition is always true. What you want is if "{01}" in line or "{-1}" in line".
I don't know what it is about Python, but your problem is one that gets posted here at least a couple times every day.
if "{01}" or "{-1}" in line:
This doesn't do what you think it does. It asks, "is "{01}" true"? Because it's a non-zero-length string, it is. Because or short-circuits, the rest of the condition is not tested because the first argument is true. Therefore the body of your if statement is always executed.
In other words, Python evaluates as if you'd written this:
if ("{01}") or ("{-1}" in line):
You want something like:
if "{01}" in line or "{-1}" in line:
Or if you have a lot of similar conditions:
if any(x in line for x in ("{01}", "{-1}")):
you can use count argument of replace():
'USC_45774-1111-0 <hkxhk> {10} ; 78'.replace("hk","kh",1)
For your second question, you need change the condition to:
if "{01}" in line or "{-1}" in line:
...