我有一個字符串存儲在一個變量中。有沒有一種方法可以讀取特定大小的字符串,例如文件對象有f.read(大小),可以讀取一定的大小?在Python中讀取字符串達到一定大小
0
A
回答
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)
相關問題
- 1. 讀取未知大小的字符串
- 2. python獲取unicode字符串大小
- 3. 如何在C++中讀取未知大小的字符串
- 4. 在python字符串中找到混合大小寫的字
- 5. 將文件讀取到字符串(python)
- 6. 讀取一串字符串
- 7. 將字符串讀入字符數組,然後獲取字符串的大小
- 8. 從Python中的字符串中讀取子字符串
- 9. JAVA:從字符串中讀取字符串到某個字符
- 10. C#中的固定字符串大小#
- 11. 需要從隨機大小字符串中提取字符串
- 12. 從Python讀取字節字符串
- 13. 在Android中獲取一個字符串的ems大小
- 14. 如何讀取大文件到一個字符串
- 15. 如何在python中替換大小寫字符串,目標字符串在?
- 16. 讀字符串在Python
- 17. 從Node.js中的文件末尾讀取確定的字符串大小
- 18. 讀取字符串中的特定行?
- 19. 從字符串中讀取特定行
- 20. Python中達到一個大寫的字
- 21. 閱讀,找到字符串,然後讀取字符串
- 22. 在java中獲取字符串數組中單個字符串的大小?
- 23. python程序讀取一個字符串,並返回另一個字符串
- 24. 從大字符串讀取行
- 25. 如何在讀取特定字符串後添加字符串?
- 26. 如何讀取動態大小的字符串流?
- 27. 從標準輸入讀取任意大小的字符串?
- 28. 從大字符串提取字符串oracle正則表達式
- 29. 基於在python塊大小逆轉在python字符串
- 30. 熊貓數據幀讀取大字符串作爲字符串
切片符號不會溢出一個字符串:'s ='f'* 5; t = s [:50]' –
是的,我想要類似子字符串,但使用給定的字節大小 – Boeingfan
你確定你想要字節而不是字符? (別忘了unicode) – ThinkChaos