Adding '0' to binary - python

How can i add number of '0' values to the left side of an existing binary type?
im getting the binary type by using the following:
binary=bin(int(symbol))
where symbol is an int.
is there any way of doing that?
i want the result to be a string.

There is no binary type, the result of bin() is a string. Here is how you can add additional zeroes to the end of a string:
>>> bin(11)
'0b1011'
>>> bin(11) + '0000'
'0b10110000'
Since it sounds like you want to add the zeroes on the left side, I'm assuming that you are doing this so that the resulting strings are the same length regardless of the value for symbol.
One good way to do this is to use str.format() instead of the bin() function, here is an example where there are always eight digits in the resulting string, and the 0b prefix is still there as if you had used bin():
>>> '0b{0:0>8b}'.format(3)
'0b00000011'
>>> '0b{0:0>8b}'.format(11)
'0b00001011'

Not exactly sure what you want, adding '0' to where.
print bin(1<<8)
print bin(1).zfill(8).replace("b", "")
Hope that helps. ~Ben

Related

How to grab hex value in between a bunch of zeros and convert it to decimal?

I wanted to try and grab a hex value in between a bunch of zeros and convert it to decimal. Here's a sample: '00000000002E3706400000'. So I only want to grab '2E37064' and disregard everything else around it. I know to use the int() function to convert it to decimal, but when I do, it includes the leading zeros right after the actual hex value. Here's a sample of my code:
hex_val = '00000000002E3706400000'
dec_val = int(hex_val, 16)
print(dec_val)
And then here's the output:
50813862936576
The actual value I want is:
48459876
Is there an optimal way to accomplish this?
You can use the .strip() function to remove the leading and trailing zeroes (though removing the leading zeroes here isn't technically necessary):
int(hex_val.strip('0'), 16)
This outputs:
48459876

Keep zero digit save while converting string to integer in python

I am converting a string into integer using int function and it is working fine but i want to keep save zero digit that are at the start of the string.
string_value = '0123'
print(int(string_value))
result is 123
How can i format output 0123 as in integer type value not in string.
You can't, but if you want to put 0's (zero padding) at the beginning of your number, this is the way to do it.
"{:04}".format(123)
# '0123'
"{:05}".format(123)
# '00123'
Like every one said you can try above answers or the following :
string_value = '0123'
int_no = int(string_value)
print("%04d" % int_no)
print(string_value.zfill(4))
Both will give same answer
Impossible, you cannot get an integer value of 0123.
You should change your mind, you do not actually need 0123 in integer, but you need to keep zero when displaying it. So the question should change to how to format output.

Representing a word as sequence of bits

I want to represent a word as a sequence of 26 bits. If 25th bit is set it means that the letter 'y' is present in that word.
For example: word:"abekz"
representation:10000000000000010000010011
This is very easy to do it in C/C++ since it has a 32 bit int type. But Python's int has infinite precision so I'm unable to do it.
Here's my (Wrong)solution:
def representAsBits(string):
mask=0
for each_char in string:
bit_position= ord(each_char)-97 #string consists of only lower-case letters
mask= mask | (1<<bit_position)
return bin(mask)
print representAsBits("abze")# gives me 0b10000000000000000000010011
print representAsBits("wxcc")# gives me 0b110000000000000000000100 2 bits missing here
What changes can I make? Thanks!
You can't store leading zeroes on an integer. Thankfully, you're using bin(), which returns a string.
With a little creative slicing, we can format it however we want:
return "0b%32d" % int(bin(mask)[2:])
will give:
>>> representAsBits("abekz")
'0b00000010000000000000010000010011'
That being said, to compare masks, you don't have to bin() them except if you want to "show" the binary. Compare the integers themselves, which will be the same:
with return mask:
>>> representAsBits("z") == representAsBits("zzz")
True
Although, since the masks will match, it doesn't matter what padding you use, as they will be the same if generated from the same mask: Any string containing only the characters wxc will yield the same string, regardless of what method you use.

Best way to add a "+" and "-"?

What is the best way to display either a + in front, for a float? Lets say if a user inputs the number "10". I want to have a "+" appear in front of it since it is a positive number. If it were a negative number then I would leave it as it is.
Would I have to use an if statement and then convert it to a string and then add in the + sign? Or is there an easier way?
Use the format() function:
>>> format(10, '+f')
'+10.000000'
>>> format(-10, '+f')
'-10.000000'
>>> format(3.14159, '+.3f')
'+3.142'
See the Format Specification Mini-Language for the specific formatting options; prepending a number format with + makes it include a plus for positive numbers, - for negative. The last example formats the number to use 3 decimals, for example.
If you need to remove the negative sign, you'd have to do so explicitly using .lstrip():
>>> format(10, '+f').lstrip('-')
'+10.000000'
>>> format(-10, '+f').lstrip('-')
'10.000000'
but that'd be quite confusing a specification to read, in my opinion. :-)
Use formatting - and then remove any leading - from the result:
print format(10, '+').lstrip('-')
The first thing I thought:
userInput=int(input("Enter number: "))
if userInput > 0:
print ("+"+userInput)
else:
pass
Formatting is just the way to go though, faster and cleaner.

Python: How to refer to a digit in a string by its index?

I feel like this is a simple question, but it keeps escaping me...
If I had a string, say, "1010101", how would I refer to the first digit in the string by its index?
You can get the first element of any sequence with [0]. Since a string is a sequence of characters, you're looking for s[0]:
>>> s = "1010101"
>>> s[0]
'1'
For a detailed explanation, refer to the Python tutorial on strings.
Negative indexes count from the right side.
digit = mystring[-1]
In Python, a sting is something called, subscriptable. That means that you can access the different parts using square brackets, just like you can with a list.
If you want to get the first character of the string, then you can simply use my_string[0].
If you need to get the last (character) in a string (the final 1 in the string you provided), then use my_string[-1].
If you originally have an int (or a long) and you are looking for the last digit, you are best off using % (modulous) (10101 % 10 => 1).
If you have a float, on the other hand, you are best of str(my_float)[-1]

Categories

Resources