Read string up to a certain size in Python -
i have string stored in variable. there way read string size e.g. file objects have f.read(size) can read size?
check out this post finding object sizes in python.
if wanting read string start until size max reached, return new (possibly shorter string) might want try this:
import sys max = 176 #bytes totalsize = 0 newstring = "" s = "mystringlength" c in s: totalsize = totalsize + sys.getsizeof(c) if totalsize <= max: newstring = newstring + str(c) elif totalsize > max: #string larger or same size max print newstring break
this prints 'mystring' less (or equal to) 176 bytes.
hope helps.
Comments
Post a Comment