0

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?

Sam Estep
  • 12,974
  • 2
  • 37
  • 75
Boeingfan
  • 31
  • 2

2 Answers2

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
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