Formatting Integers - python

I want to understand the logic behind the outputs of the below print statements.
x = 345
print ("%06d"%x)
print ("%-06d"%x)
The first statement would as expected prefix the number of zeroes required to make the total length as 6. The output is 000345 which I understand.
But the output of the second print statement is 345. How come? What is purpose of "-" operand?

minus means align to left.
You will see it when you add another element in print -
print("%06d"%x, 'a')
print("%-06d"%x, 'a')
Result
000345 a
345 a
See: PyFormat.info

Basically, the minus and the leading zero specify conflicting requirements. Python arbitrarily picks the minus as the winner.

Related

Why am I getting a different output when the multiplication of the digit is above 10?

#card number
card = input('Number: ')
j = int(card[::2]) # this will jump character by 1
# multiplying each other number by 2
j *= 2
print(j)
So whenever I run this code and input e.g. 1230404
The output would be correct which is 2688
But when I input for example 1230909 the output is 2798, I expected 261818
Let's look at what your code is doing.
You slice every second character from your input string, so '1230909' becomes '1399'.
You convert that to a single int, 1399.
You multiply that number by 2, producing 2798. I assure you that the computer did the math correctly.
It appears what you expected was for each digit to be doubled individually. To do that, you need to convert each digit, double it, and combine them back. Python has great facilities for this, I'd suggest a generator expression inside a join call.

How do I print numbers from 1 to n in python in a single line without spaces?

print(*range(1, int(input())+1), sep='')
This was the code I found in a discussion on hacker rank. But I did not understand it.
Can anyone please explain this?
So, from what I can tell, this is how it works:
int(input())
This takes input from the user.
Next;
range(1,...+1)
This creates a range from 1 to our number we inputted earlier. The +1 means that it will include the max number.
And then:
print(*...,sep='')
The * sign, from what I can tell, just effectively returns each value in our range one to be printed.
The sep='' just means each value is separated by '' or nothing.
Hope this is useful to you.
[EDIT]
More on star and double star expressions in this post:
What does the star and doublestar operator mean in a function call?
Ok so we have print function. Inside we have this strange *range(1, int(input())+1) this is range function which return value from 1 to n (n is typed in input) in a form of a range object. * unpack this object to form like: 1 2 3 4 ... with spaces, so we have this sep='', keyword argument that makes separation from space to '' (no separate between).
Also you can do it like that:
n = input("Type integer value: ")
try:
[print(x+1,end="") for x in range(int(n))]
except ValueError:
exit("Typed string not number")

Project Euler #13 Python. Incorrect carry over

This problem asks to sum up 100 numbers, each 50 digits long. http://code.jasonbhill.com/python/project-euler-problem-13/
We can replace \n with "\n+" in Notepad++ yielding
a=37107287533902102798797998220837590246510135740250
+46376937677490009712648124896970078050417018260538
...
+20849603980134001723930671666823555245252804609722
+53503534226472524250874054075591789781264330331690
print(a)
>>37107287533902102798797998220837590246510135740250 (incorrect)
We can as well replace \n with \na+= yielding
a=37107287533902102798797998220837590246510135740250
a+=46376937677490009712648124896970078050417018260538
...
a+=20849603980134001723930671666823555245252804609722
a+=53503534226472524250874054075591789781264330331690
print(a)
>>553... (correct)
This seems to be a feature of BigInteger arithmetic. Under which conditions a sum of all numbers (Method 1) yields different result from an iterative increment (Method 2)?
As you can see in the result, the first set of instruction is not computing the sum. It preserved the first assignment. Since +N is on its own a valid instruction, the next lines after the assignment do nothing. Thus
a=42
+1
print a
prints 42
To write an instruction over two lines, you need to escape the ending newline \n :
a=42\
+1
43
Python source code lines are terminated by newline characters. The subsequent lines in the first example are separate expression statements consisting of a single integer with a unary plus operator in front, but they don't do anything. They evaluate the expression (resulting in the integer constant itself), and then ignore the result. If you put all numbers on a single line, or use parentheses around the addition, the simple sum will work as well.

Sum of parts of a string in Python

I'm learning to program using the book "Introduction to computation and programming using Python" by John V. Guttag. There is an exercise on it that says the following:
'Finger exercise: Let s be a string that contains a sequence of
decimal numbers separated by commas, e.g., s = '1.23,2.4,3.123'. Write
a program that prints the sum of the numbers in s.'
My try was:
#Finger exercise [MIT] PAGE 42 12:50 | 11.10.2015
s = ','+raw_input('Enter a string that contains a sequence of decimal numbers separated by commas, e.g. 1.23,2.4,3.123): ')+','
total = 0
for l in range(0,len(s)):
if s[l] == ',':
c = l + 1
while s[c] != ',':
c = c + 1
if s[c] == ',':
total = total + int(s[int(l),int(c)])
print total
but it keeps showing this error
TypeError: string indices must be integers, not tuple
I've tried to seek solutions online but only found solutions that work but not with the content I already now.
Any help?
You are creating a tuple when accessing your string item here:
s[int(l),int(c)]
Commas generally create tuples.
Instead, you want to use a slice here using a colon:
s[int(l):int(c)]
Note that both variables are already integers, so you don't actually need to convert them:
s[l:c]
Also note that you are summing integer values although you accept floats as the input. So instead of adding int(s[l:c]) you want to add float(s[l:c]).
First of all, there is no processing of anything before the first comma.
Next, you should comment each part of it at least initially to you are clear what each line is doing.
You shouldn't need to check for a ',' in multiple places, keep a variable.
A solution I found, hope its useful:
s = "1.23, 2.4, 3.123"
news = s.split(",")
total = 0
for string in range(len(news)):
total += float(news[string])
print(total)

python string formatting fixed width

I want to put a bunch of floating point numbers into a fixed-width table. That is, I want a maximum of 12 characters used. I want a minimum of 10 decimals used (if available); however, if 10 decimals makes it take up more than 12 characters, then round. My original thought was to try something like this
# I only want 12 characters used total
num1 = 0.04154721841
num2 = 10.04154721841
# not what I want
print "{:<12.11g}".format((num1))
# what I want
print "{:<12.10f}".format((num1))
# not what I want
print "{:<12.10f}".format((num2))
# what I want
print "{:<12.11g}".format((num2))
There has to be a way to achieve this without writing a function to check every number and give formatting based on the above conditions. What am I missing?
I'm not sure this is what you are looking for, since it's not accomplished entirely with the format string, however, you could just use string slicing to lop-off the trailing chars when things get too long:
num1 = 0.04154721841
num2 = 10.04154721841
num3 = 1002.04154721841
print "{0:<12.11g}".format(num1)[:12]
print "{0:<12.11g}".format(num2)[:12]
print "{0:<12.11g}".format(num3)[:12]
outputs:
0.0415472184
10.041547218
1002.0415472
Beyond that, I'd say you should just write a function, though I'm not an expert on the str.format stuff, so I may be missing something.

Categories

Resources