For a class I am learning how to slice integers. In the code below the variable halflength is equal to half of the length of the variable message.
new = message[halflength::]
halflength is equal to an integer, however whenever I run this code I get this error:
TypeError: slice indices must be integers or None or have an __index__ method
Basically I need to try and create a new string that is equal to the second half of the original string.
Example: original string 1234 would produce 34 as the new string.
I think the problem is you get a float type for halfLength after division, try to cast it to int, or use integer division
halfLength = int(halfLength)
or
halfLength = len(message) // 2
to do what you want to do try something like this:
halfLength=len(message)//2
newMessage=message[halfLength::]
if you get the length this way it will always be an integer that you can then use to get parts of stings with.
Make sure halflength is of type Integer.
You can use "isinstance" method to verify.
# python
Python 2.7.5 (default, Aug 2 2016, 04:20:16
>>> halflength = "4"
>>> isinstance(halflength,int)`
False`
>>> halflength=4
>>> isinstance(halflength,int)
True
>>>
Try This:
message[int(halflength)::]
Related
So I answered one of the questions on Coding Bat that asked to return half of a string n number of times by defining a variable that takes half the length of the original string and using that variable in slicing the string.
Coding bat accepted the result, but when I try to recreate the problem on Jupyter Notebook it only accepts "integers or None or index method".
What am I doing wrong?
Im a beginner in Python and just want to make sure that I'm learning the correct format.
def first_half(str):
newword = len(str) / 2
return '{}'.format(str[:newword])
for first_half('Milkshakes') I expect to get 'Milk'.
However, the error im getting is:
TypeError: slice indices must be integers or None or have an __index__ method
This is because len(str) / 2 gives you a float value 5.0 and you cannot use a float as a argument to string slice, convert the argument to an int by doing int(len(str) / 2), which gives you 5, and it should work. Note that the above only holds true for Python 3 the original code you have still works for Python 2 where you don't need the float to int conversion
Also str is a python builtin, so it's bad practice to use it as a variable.
In addition, you want the first half of Milkshakes is Milks, and not Milk
def first_half(s):
#Parse float to int
newword = int(len(s) / 2)
return '{}'.format(s[:newword])
print(first_half('Milkshakes'))
#Milks
To make a generic solution, as some of the commentors have suggested, you can use integer division //, which works for both Python 2 and Python 3
def first_half(s):
#Integer division
newword = len(s) // 2
return '{}'.format(s[:newword])
print(first_half('Milkshakes'))
I have a list by connection of two strings and then converting them to integer by:
for i in xrange(0, len(FromBus[1][0])):
FromBus[1][0][i] = int(str(FromBus[1][0][i]) + str(ToBus[1][0][i]))
List looks as following:
>>> FromBus[1][0][1:5]
[3724637724L, 3724837324L, 3724837707L, 3724837707L]
List is made of longs
>>> type(FromBus[1][0][1])
<type 'long'>
Due to post processing of data in different environment I am trying to convert the long type to integer type so I need to delete 'L' at the end of each variable.
However, all of the methods I have found, failed:
>>> int(FromBus[1][0][1])
3724637724L
>>> [int(i) for i in FromBus[1][0]][1:5]
[3724637724L, 3724837324L, 37248377071L, 37248377072L]
>>> map(int, FromBus[1][0][1:5])
[3724637724L, 3724837324L, 37248377071L, 37248377072L]
My question is, what is the source of the problem here? I can easily convert them to strings. But how can I still convert long to int, without doing it thorugh string method (convert long to strings deleting the last character at the end of each string and then converting it back again to integer).
Sufficient solution for me, would be also to manimulate csv writing function deleting 'L''s while writing.
The L is part of Python's representation of the value, to show you that it's a long(). The actual number is ... well, the actual number. So there isn't really a "suffix" to trim off.
int() will still return a long() if the value is too long to fit into an int() -- but you can use str() to get just the digits in a form which is convenient to put in a CSV file.
In fact, the Python csv module (unsurprisingly) already does something like this, so I am not altogether sure you need this for your stated scenario.
Basically any bit manipulation which has an implication of a value in the 32nd bit is said to be a long. 1 << 31 becomes a long. because the 1 there is positive and you moved it over. Likewise if you set the value above the 1^31 value it will become a long. If you perform an int operation on an out of range value it will stay a long. This is kinda annoying to old-school bit manipulators who know there's 32 bits to fiddle with shove these relevant 32 bits into that size of a register.
Python refuses to make your number negative if you just happen to fill the 32nd bit through any means that wasn't - or ~. So you need to peel off the 32nd bit force it negative with operations that won't trigger the long conversion.
def sign32neg(value):
if 0x80000000 <= value <= 0xFFFFFFFF:
value &= 0x7FFFFFFF
value = int(value)
value = ~value
value ^= 0x7FFFFFFF
return value
This will make longs that could be expressed as a 32 bit negative integer, be expressed as such.
Python 2.7.12 (default, Dec 4 2017, 14:50:18)
[GCC 5.4.0 20160609] on linux2
Type "copyright", "credits" or "license()" for more information.
>>> x = int
>>> x
<type 'int'>
>>> x = long
>>> x
<type 'long'>
>>> print x
<type 'long'>
>>>
So :
import struct
my_val, = struct.unpack('>d', my_string_part_if shorter_than_4Bytes_fill_\x00))
Another way :
>>> import binascii
>>> print int(binascii.hexlify("test"),16)
1952805748
>>>
**#be carefull always length 4 bytes**
I want to convert an integer to a number in ZP group. I have written following code but it is returning a number of <class 'integer.Element'> type. Can someone tell me how can I do this?
num= 193857774579808121448
bb= Conversion. IP2OS(num, 20)
ele= Conversion.OS2IP(bb, element=True)
You can use PairingGroup.init(ZR, 193857774579808121448) to convert a Python integer to a Charm element in Zr.
Example:
>>> from charm.toolbox.pairinggroup import PairingGroup,ZR,G1,G2,GT,pair
>>> group = PairingGroup('SS512')
>>> i = group.init(ZR, 193857774579808121448)
>>> i
193857774579808121448
>>> type(i)
<class 'pairing.Element'>
Keep in mind that the Python integer that you pass in must be smaller than r which is shown in the pairing parameters (i.e. group.__dict__). Charm will silently apply the modulo operator to the passed number so that the resulting element is in Zr.
I have a string in the format: 'nn.nnnnn' in Python, and I'd like to convert it to an integer.
Direct conversion fails:
>>> s = '23.45678'
>>> i = int(s)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '23.45678'
I can convert it to a decimal by using:
>>> from decimal import *
>>> d = Decimal(s)
>>> print d
23.45678
I could also split on '.', then subtract the decimal from zero, then add that to the whole number ... yuck.
But I'd prefer to have it as an int, without unnecessary type conversions or maneuvering.
How about this?
>>> s = '23.45678'
>>> int(float(s))
23
Or...
>>> int(Decimal(s))
23
Or...
>>> int(s.split('.')[0])
23
I doubt it's going to get much simpler than that, I'm afraid. Just accept it and move on.
What sort of rounding behavior do you want? Do you 2.67 to turn into 3, or 2. If you want to use rounding, try this:
s = '234.67'
i = int(round(float(s)))
Otherwise, just do:
s = '234.67'
i = int(float(s))
>>> s = '23.45678'
>>> int(float(s))
23
>>> int(round(float(s)))
23
>>> s = '23.54678'
>>> int(float(s))
23
>>> int(round(float(s)))
24
You don't specify if you want rounding or not...
You could use:
s = '23.245678'
i = int(float(s))
"Convert" only makes sense when you change from one data type to another without loss of fidelity. The number represented by the string is a float and will lose precision upon being forced into an int.
You want to round instead, probably (I hope that the numbers don't represent currency because then rounding gets a whole lot more complicated).
round(float('23.45678'))
The expression int(float(s)) mentioned by others is the best if you want to truncate the value. If you want rounding, using int(round(float(s)) if the round algorithm matches what you want (see the round documentation), otherwise you should use Decimal and one if its rounding algorithms.
round(float("123.789"))
will give you an integer value, but a float type. With Python's duck typing, however, the actual type is usually not very relevant. This will also round the value, which you might not want. Replace 'round' with 'int' and you'll have it just truncated and an actual int. Like this:
int(float("123.789"))
But, again, actual 'type' is usually not that important.
I believe this is a useless bug that should be corrected in Python.
int('2') --> 2 That converts the string '2' into an the integer 2.
int(2.7) --> 2 Converts a float to an int.
int('2.7') SHOULD convert to 2. This is how Perl works, for example. Yes, this does two things at once. It converts the string and when it finds it is in a representation that is a float, it should convert to int.
Otherwise, why insist that float('2') should work? It is an integer string, because there is no decimal point. So it has to convert from string which is an integer, directly to float.
I don't know but perhaps someone can answer whether the python interpreter, if the required int(float(x)) is used, if it actually goes through the process of first converting to float and then converting to int. That would make this bug even more critical to correct.
I'm fairly weak with structs but I have a feeling they're the best way to do this. I have a large string of binary data and need to pull 32 of those chars, starting at a specific index, and store them as an int. What is the best way to do this?
Since I need to start at an initial position I have been playing with struct.unpack_from(). Based on the format table here, I thought the 'i' formatting being 4 bytes is exactly what I needed but the code below executes and prints "(825307441,)" where I was expecting either the binary, decimal or hex form. Can anyone explain to me what 825307441 represents?
Also is there a method of extracting the data in a similar fashion but returning it in a list instead of a tuple? Thank you
st = "1111111111111111111111111111111"
test = struct.unpack_from('i',st,0)
print test
Just use int
>>> st = "1111111111111111111111111111111"
>>> int(st,2)
2147483647
>>> int(st[1:4],2)
7
You can slice the string any way you want to get the indices you desire. Passing 2 to int tells int that you are passing it a string in binary