Truncate A String To A Specific Number Of Bytes In Python
How can I truncate a string to be no longer than 50 bytes? a = 'asdfzx안녕하세요awelkjawletjawetr방갑습니다.dlgawklejtwgasdgsdfgd sdfasdfsdafa궁금해요rewgargasregaw
Solution 1:
You could just use slicing if you are using a one character per byte encoding:
a = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
a[:50]
'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
Note that would only makes sense if you are writing this somewhere. If the size of the python object representation makes more sense in your use-case, the answer of @Achilles should works.
Solution 2:
You can use getsizeof()
to get the size and then put it in a if statement to check.getsizeof()
returns the size of an object in bytes.Hope my example gives you an idea :
from sys importgetsizeofa='4200547985984359347509gbrtbhrtbrtbargrefefwefwef'
b = 'hello'ifgetsizeof(a.encode('ascii')) > 50 :
print("Error:a")
ifgetsizeof(b.encode('ascii')) > 50 :
print("Error:b")
Post a Comment for "Truncate A String To A Specific Number Of Bytes In Python"