Removing period from number in python - python

Given a real number between 0 and 1 (for example 0.2836) I want to return only the number without the dot (for example in this case from 0.2836 -> 2836 or 02836). I was trying to use python to do this but I just started and I need some help.

As long as you have a number, the following should do:
>>> number = 0.2836
>>> int(str(number).replace('.', ''))
2836
If a . is not found in the string, str.replace just returns the original string.
With more numbers:
>>> int(str(1).replace('.', ''))
1
>>> int(str(1.2).replace('.', ''))
12

The simplest way to remove an unwanted character from a strip is to call its .replace method with an empty string as the second argument:
x = str(123.45)
x = x.replace('.','')
print(x) # Prints 12345
Note, this would leave any leading zeros (i.e. 0.123 using this method would result in 0123)
If you know there are always, say, 4 numbers after the decimal (and in the case that there are less, you want trailing zeros), you could multiply the number by an appropriate factor first:
x = 123.4567
x *= 10000
x = str(int(x)) # Convert float to integer first, then to string
print(x) # Prints 1234567
There are other options, but this may point you in the right direction.

Related

Print binary value Python

I already tried converting it to a string, adding 0 to it, but it still only shows me the decimal value, how can I make it show me its binary value?
If I try this:
binary = 0b010
print(binary)
or this:
binary = 0b010
print(str(binary))
which outputs this:
2
I also tried this:
binary = 0b010
print("{0:b}".format(binary))
which outputs this:
10
Desired output:
010
The bad part is that it does not fill in the number of 0 on the left, it gives me an output of 10 when I want 010, but I want it to show the number of 0 possible for any binary that I put.
I'm new to Python, but every time I look for how to do it, it only appears to me as converting from integer to binary and showing it. But I can't use the bin() function, so I resorted to asking it here directly, thanks for your understanding.
You have a couple of ways of going about it.
The one that fits your use case the best is the format() method:
binary = 0b010
print("{:03b}".format(binary))
Which outputs:
010
Changing the 3 in {:03b} will change the minimum length of the output(it will add leading zeros if needed).
If you want to use it without leading zeros you can simply do {:b}.
You can try defining your own function to convert integers to binary:
def my_bin(x):
bit = ''
while x:
bit += str(x % 2)
x >>= 1
return '0' + bit[::-1]
binary = 0b010
print(my_bin(binary))
Output:
010

Add one to end of alphanumeric string in Python

I'm trying to efficiently add one to the end of a string like this:
tt0000001 --> tt0000002 but I'm not sure how to accomplish this.
A complicated way of doing this is to remove the 2 t's at the beginning, count the number of non-zero digits (let's call that number z), make the string an int, add 1, and then create a string with 2 t's, 6 - z 0's, and then the int, but since I need to use many strings (ex: tt0000001, then tt0000002 then tt0000003, etc) many times, it would be great to have a more efficient way of doing this.
Would anyone know how to do this? A one-liner would be ideal if possible.
Thank you!
What you describe is essentially correct. It's not as difficult as you suggest, though, as creating a 0-padded string from an integer is supported.
As long as you know that the number is 7 digits, you can do something like
>>> x = 'tt0000001'
>>> x = f'tt{int(x.lstrip("t"))+1:07}'
>>> x
'tt0000002'
Even simpler, though, is to keep just an integer variable, and only (re)construct the label as necessary each time you increment the integer.
>>> x = 1
>>> x += 1
>>> f'tt{x:07}'
'tt0000002'
>>> x += 1
>>> f'tt{x:07}'
'tt0000003'

Formatting a float number without trailing zeros

When I do a simple division in Python 3, such as 123000/1000, I get 123.0, or 4/2 I get 2.0. How do I get rid of the trailing zero in Python 3's division?
EDIT:
I don't want just simple integer division. For ex, 1234/1000 should give 1.234.
To be clear, this question is about formatting the output, not internal representation.
Thanks all for your help! The answer came from #vaultah:
>>> f'{2.1:g}'
'2.1'
>>> f'{2.0:g}'
'2'
So just use regular division such as 4/2 and then format the string.
From the docs for 'g': https://docs.python.org/2/library/string.html#format-specification-mini-language
"insignificant trailing zeros are removed from the significand, and the decimal point is also removed if there are no remaining digits following it."
You could use something like this:
def remove_trailing_zeros(x):
return str(x).rstrip('0').rstrip('.')
remove_trailing_zeros(1.23) # '1.23'
remove_trailing_zeros(4.0) # '4
Normally, you would use standard string formatting options like '%2.1f' % number or any of the other many ways to format a string. However, you would then have to specify the amount of digits you want to display but in this case the number of trailing zeros to return is variable. The '%g' format specifier does not have this problem, but uses scientific notation and I don't know if that is what the OP wants.
The above solution converts the number to a "nicely printable string representation" (str(x)), and then removes trailing zeros (.rstrip('0')) and if necessary the remaining trailing period (.rstrip('.')) (to avoid "1." as a result) using standard string methods.
It's "correct" behaviour to have "floats" as a result, and .0 part simply indicates this fact. I think that what matter to you is "representation" of the result in the string. So you should not change actual result and only change the way it's "displayed". Use formatting mini language:
>>> for val in (123000/1000, 4/2, 1234/1000): print(f"{val:g}") # Use "General format" to represent floats
...
123
2
1.234
Mod is an O(1) operation which should add almost no overhead to your actual program. You could make it into a one liner also
x = a//b if not a % b else a/b
If you need to do this kind of thing a lot, make it into a function
def func(a, b):
return a//b if not a % b else a/b
func(10, 2) # out = 5
func(10, 3) # out = 3.333333333
func(1200, 100) # out = 12
func(1234, 1000) # out = 1.234
This works well for me. No scientific notation format for big numbers.
def no_trailing_zero(value: float) -> Union[float, int]:
return int(value) if value % 1 == 0 else float(str(value))
>>> no_trailing_zero(50)
50
>>> no_trailing_zero(50.11)
50.11
>>> no_trailing_zero(50.1100)
50.11
>>> no_trailing_zero(50.0)
50
>>> no_trailing_zero(500000000.010)
500000000.01
>>>
If you can guarantee that you get just a trailing zero, casting to int gets rid of it:
>>> 4/2
2.0
>>> int(4/2)
2
# // => used for integer output
# / => used for double output
x = 100/35 # => 2.857142857142857
y = 100//35 # => 2
z = 100.//35 # => 2.0 # floating-point result if divisor or dividend real

How to display last 2 digits from a number in Python

I am trying to take air pressure readings and plot them with their last 2 digits showing. However, when I use modulo:
--> x = 1004
--> x % 100
--> 4
This just generates 4.
How can I display this to show 04 instead of 4?
Thanks!
Try the following:
str(x%100).zfill(2)
If you need it as an int or a float, I don't think this is possible. If it's only for display purposes, convert it to a string and take the last 2 characters:
x = 1004
>>> str(x)[-2:]
'04'
If you just print out a number, it prints it out in its default format. For the number 2, that's obviously going to be 2, not 02.
If you want to specify a custom format, you need to use some form of string formatting. Python has a few ways to do it.
Format Strings
The same Format String Syntax is used by the format function, the str.format method, Formatter subclasses, and (with slight differences that aren't relevant here) f-string literals.
You can specify a width of 2, plus an align of = (meaning numeric alignment—padding is placed after any + or -) and a fill of 0. But there's also a special shortcut, where placing a 0 right before the width means numeric-aligned zero-fill. So:
>>> f"{x % 100:02}"
'02'
>>> format(x % 100, '02')
'02'
>>> '{:02}'.format(x % 100)
'02'
printf-style String Formatting
Python has an older, but still sometimes useful, way to do formatting,1 which more closely matches that of C and similar languages, calling printf-style or %-formatting.
You specify a width of 2, and a flag of 0, which indicates numeric zero-padding, together with a type of d to specify that you want to format the number as a signed integer decimal:
>>> "%02d" % (x % 100,)
'02'
While %-formatting isn't as flexible and powerful as format strings, it can sometimes be simpler to understand (especially if you're used to C or another language), is often faster, and works with bytes as well as str.
Manual string operations
Finally, you can always convert the number to a string and then use string methods on it. For example, you can use the zfill method to zero-fill a string:
>>> str(x % 100).zfill(2)
'02'
… or you can use the rjust method to right-justify it with '0' as a fill character:
>>> str(x % 100).rjust(2, '0')
'02'
In fact, instead of calculating the remainder, you could just convert the whole thing to a string, truncate it, then zero-fill:
>>> str(x)[-2:].zfill(2)
… although this probably won't be what you want is x is, say, -123 (you'll get 23 instead of 77).
1. In fact, it provides two older solutions, the other being template strings, but these aren't useful as often.
The shortest way to do this is '%02d' % (x % 100)
x = 1004
x = x % 100
str(x)
y = len(x)
if y == 0:
end
elif y == 2:
print (x)
elif y == 1:
print ('0'x)
else:
x = str(x)[-2:]
print (x)
In this, I've converted it into a string & calculated the length of the value as 'y'. Using a basic [if elif else] structure I have returned the values in your format, but as strings.
It is unclear what you wanted to use these values for because if you want them to represent figures you will probably need to edit the settings of whatever output application you are using. An alternative solution would be to use the value for 'x' as being different to the string so that the number value can still be used regardless of the way it is displayed when printing. wink, wink.
You could use string formatting too.
ans = 1004 % 100
format(ans, '03d')
More information about String formatting can be found here: https://pyformat.info/
No modulo, no zfill.
"{:02d}".format(12345)[-2:]
#> 45
"{:02d}".format(0)[-2:]
#> 00
"{:02d}".format(-9876)[-2:]
#> 76
"{:02d}".format(-1)[-2:]
#> -1
Your first step to use the modulus operator to find the two-least significant digits is correct.
Then you'll want to use a format string to pad your result when printing it. See: Python format Integer into fixed length strings

How do I use string formatting to show BOTH leading zeros and precision of 3?

I'm trying to represent a number with leading and trailing zeros so that the total width is 7 including the decimal point. For example, I want to represent "5" as "005.000". It seems that string formatting will let me do one or the other but not both. Here's the output I get in Ipython illustrating my problem:
In [1]: '%.3f'%5
Out[1]: '5.000'
In [2]: '%03.f'%5
Out[2]: '005'
In [3]: '%03.3f'%5
Out[3]: '5.000'
Line 1 and 2 are doing exactly what I would expect. Line 3 just ignores the fact that I want leading zeros. Any ideas? Thanks!
The first number is the total number of digits, including decimal point.
>>> '%07.3f' % 5
'005.000'
Important Note: Both decimal points (.) and minus signs (-) are included in the count.
This took me a second to figure out how to do #nosklo's way but with the .format() and being nested.
Since I could not find an example anywhere else atm I am sharing here.
Example using "{}".format(a)
Python 2
>>> a = 5
>>> print "{}".format('%07.3F' % a)
005.000
>>> print("{}".format('%07.3F' % a))
005.000
Python 3
More python3 way, created from docs, but Both work as intended.
Pay attention to the % vs the : and the placement of the format is different in python3.
>>> a = 5
>>> print("{:07.3F}".format(a))
005.000
>>> a = 5
>>> print("Your Number is formatted: {:07.3F}".format(a))
Your Number is formatted: 005.000
Example using "{}".format(a) Nested
Then expanding that to fit my code, that was nested .format()'s:
print("{}: TimeElapsed: {} Seconds, Clicks: {} x {} "
"= {} clicks.".format(_now(),
"{:07.3F}".format((end -
start).total_seconds()),
clicks, _ + 1, ((_ + 1) * clicks),
)
)
Which formats everything the way I wanted.
Result
20180912_234006: TimeElapsed: 002.475 Seconds, Clicks: 25 + 50 = 75 clicks.
Important Things To Note:
#babbitt: The first number is the total field width.
#meawoppl: This also counts the minus sign!...
[Edit: Gah, beaten again]
'%07.3F'%5
The first number is the total field width.

Categories