我有一个大小为5gb的字符串,我想获得字符串的最后30个字符。使用切片函数是最好的方式来获得子字符串,它会导致内存问题吗?是否因为在拆分过程中创建了4.99 GB和0.1 kb的子字符串,所以将创建另外5gb ?
str.split()
创建一个列表。因此,您最终将得到至少5GB的字符串和5GB的列表,以及进程中使用的内存。获取字符串的最后一个x
字符的最好方法是负索引。
x = 30
last_30_characters = very_long_string[-x:]
编辑:对列表进行切片不会生成副本,因此,在最大情况下,它应该只使用原始字符串所需的内存。源。
我相信你可以使用负索引。
sample_string = 'hello there'
print(sample_string[-3:])
您可以使用字符串切片获得最后30个字符,例如name_of_string[-30:]来切片最后30个字符。这不会为字符串的其余部分创建一个新对象。
我假设您已经将字符串存储在文件中。
即使没有n
分隔它们,您也不必将整个字符串加载到内存中。这个链接很有帮助:https://docs.python.org/3/tutorial/inputoutput.html
例如,text.txt
文件包含0123456789n
作为其内容。
with open('text.txt', 'rb') as f:
f.seek(-4, 2) # move the file cursor to the 4th last byte.
# read the rest string into memory, strip trailing newline, decode to normal string
text = f.read().strip().decode("utf-8")
print(text) # '789'
你需要调整它来适应你的应用。