python 的 slice 函数在这种情况下是否使用大量内存?

Does python's slice function uses a lot of memory in this case?

我有一个大小为 5 GB 的字符串,我想获取该字符串的最后 30 个字符。使用 slice 函数是获取该子字符串的最佳方法,它会导致内存问题吗?是否因为在拆分过程中创建了一个4.99 GB和一个0.1 kb的子串,还会创建另一个5 GB?

我相信你可以使用负索引。

sample_string = 'hello there'

print(sample_string[-3:])

您可以使用字符串切片获取最后 30 个字符,例如name_of_string[-30:] 分割最后 30 个字符。这不会为字符串的其余部分创建新对象。

str.split() 创建一个列表。因此,您最终至少会得到一个 5GB 的字符串和一个 5GB 的列表,再加上该过程中使用的任何内存。获取字符串最后 x 个字符的最佳方法是负索引。

x = 30
last_30_characters = very_long_string[-x:]

编辑: 切片列表不会生成副本,因此最多只能使用原始字符串所需的内存。 Source.

我假设您已将字符串存储在文件中。

您不必将整个字符串加载到内存中,即使没有 \n 分隔它们也是如此。这个 link 很有帮助:https://docs.python.org/3/tutorial/inputoutput.html

例如,text.txt 文件包含 0123456789\n 作为其内容。

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'

您需要根据您的应用进行调整。