I have a string stored in a variable. Is there a way to read a string up to a certain size e.g. File objects have f.read(size) which can read up to a certain size?
            Asked
            
        
        
            Active
            
        
            Viewed 803 times
        
    0
            
            
        - 
                    3Slice notation won't overrun a string: `s = 'f' * 5; t = s[:50]` – anthony sottile Feb 05 '16 at 16:23
- 
                    Yes I want something like substring but using the given size in bytes – Boeingfan Feb 05 '16 at 16:25
- 
                    Are you sure you want bytes and not characters? (Don't forget unicode) – ThinkChaos Feb 05 '16 at 16:31
- 
                    I want characters. Note the size is in bytes – Boeingfan Feb 05 '16 at 16:32
- 
                    Basically I want send a string over a socket so I need to split my string in chunks – Boeingfan Feb 05 '16 at 16:37
2 Answers
0
            
            
        Check out this post for finding object sizes in python.
If you are wanting to read the string from the start until a certain size MAX is reached, then return that new (possibly shorter string) you might want to try something like this:
import sys
MAX = 176 #bytes
totalSize = 0
newString = ""
s = "MyStringLength"
for c in s:
    totalSize = totalSize + sys.getsizeof(c)
    if totalSize <= MAX:
        newString = newString + str(c)
    elif totalSize > MAX:
        #string that is slightly larger or the same size as MAX
        print newString
        break    
This prints 'MyString' which is less than (or equal to) 176 Bytes.
Hope this helps.
        Community
        
- 1
- 1
        Benjamin Castor
        
- 234
- 3
- 9
- 
                    Just saw you want 'size' in characters and not bytes. John's post then seems more appropriate. – Benjamin Castor Feb 05 '16 at 19:38
0
            
            
        message = 'a long string which contains a lot of valuable information.'
bite = 10
while message:
    # bite off a chunk of the string
    chunk = message[:bite]
    # set message to be the remaining portion
    message = message[bite:]
    do_something_with(chunk)
        John Gordon
        
- 29,573
- 7
- 33
- 58