2016-02-05 15 views
0

我有一个字符串存储在一个变量中。有没有一种方法可以读取特定大小的字符串,例如文件对象有f.read(大小),可以读取一定的大小?在Python中读取字符串达到一定大小

+3

切片符号不会溢出一个字符串:'s ='f'* 5; t = s [:50]' –

+0

是的,我想要类似子字符串,但使用给定的字节大小 – Boeingfan

+0

你确定你想要字节而不是字符? (别忘了unicode) – ThinkChaos

回答

0

检出this发现在python中的对象大小。

如果你想读,直到一定的规模达到MAX开始的字符串,然后返回一个新的(可能是较短的字符串),你可能想尝试这样的事:

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  

这版画'MyString'小于(或等于)176字节。

希望这会有所帮助。

+0

只是看到了'字符大小'而不是字节。约翰的帖子似乎更合适。 –

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) 
相关问题