2016-02-05 16 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) 
相關問題