python中的split方法

2024-10-02 18:15:40 发布

您现在位置:Python中文网/ 问答频道 /正文

有人知道语句huck_finn_text.split('CHAPTER ')[44: ]中的[44:]在做什么,为什么

    huck_finn_url = 'https://bitbucket.org/bakuzen/bsu-fds/raw/master/lec/huck_finn.txt'
    huck_finn_text = read_url(huck_finn_url)
    huck_finn_chapters = huck_finn_text.split('CHAPTER ')[44:]

    # Display the chapters of Huckleberry Finn in a table.
    Table().with_column('Chapters', huck_finn_chapters)

输出为 enter image description here


Tags: texthttpsorgurlbitbucketraw语句split
3条回答

^{}拆分字符串,以便查找所有出现的'CHAPTER '(即字母“CHAPTER”后跟空格),并返回它们之间所有文本的列表

something[a:b]slice operation,它意味着从数字a到数字b的所有项目。例如,如果a = [3, 4, 5, 6, 7],那么a[2:4] == [5, 6]。您可以省略第一个数字以从开始开始获取所有内容,或者省略第二个数字以获取所有内容直到结束。在本例中,some_list[44:]表示跳过前44项,然后返回其余项

它被称为slicing

在本例中,您正在切片一个列表:

huck_finn_chapters = huck_finn_text.split('CHAPTER ')[44:]

您正在将列表从44索引分割到末尾

看看这个答案:https://stackoverflow.com/a/509295/11101156

split方法在url中用一个字符或一个单词分隔文本,这里是“Chapter”

您可以在此处阅读: https://www.w3schools.com/python/ref_string_split.asp

相关问题 更多 >