.split(“,”)分隔字符串的每个字符

2024-09-24 12:28:26 发布

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

在程序的某一点上,我要求它接受用户的文本输入,并根据其逗号分隔文本,然后再次将其放入txt文件中。这样做的目的是建立一个包含所有逗号分隔信息的列表。在

问题是,显然,当我",".join时,它用逗号分隔每个字符,所以如果我有一个字符串info1,info2,它就会分离,得到info1 | info2,但是当再次连接它时,它的结尾像i,n,f,o,1,,,i,n,f,o,2,,这是高度不可纠错的,因为它从txt文件中获取文本,以便在程序中稍后显示给用户。有人能帮我吗?在

        categories = open('c:/digitalLibrary/' + connectedUser + '/category.txt', 'a')
        categories.write(BookCategory + '\n')
        categories.close()
        categories = open('c:/digitalLibrary/' + connectedUser + '/category.txt', 'r')
        categoryList = categories.readlines()
        categories.close()

            for category in BookCategory.split(','):
                for readCategory in lastReadCategoriesList:
                    if readCategory.split(',')[0] == category.strip():
                        count = int(readCategory.split(',')[1])
                        count += 1
                        i = lastReadCategoriesList.index(readCategory)
                        lastReadCategoriesList[i] = category.strip() + "," + str(count).strip()
                        isThere = True
                if not isThere:
                    lastReadCategoriesList.append(category.strip() + ",1")
                isThere = False

            lastReadCategories = open('c:/digitalLibrary/' + connectedUser + '/lastReadCategories.txt', 'w')
            for category in lastReadCategoriesList:
                if category.split(',')[0] != "" and category != "":
                    lastReadCategories.write(category + '\n')
            lastReadCategories.close()

        global finalList

        finalList.append({"Title":BookTitle + '\n', "Author":AuthorName + '\n', "Borrowed":IsBorrowed + '\n', "Read":readList[len(readList)-1], "BeingRead":readingList[len(readingList)-1], "Category":BookCategory + '\n', "Collection":BookCollection + '\n', "Comments":BookComments + '\n'})

        finalList = sorted(finalList, key=itemgetter('Title'))

        for i in range(len(finalList)):
            categoryList[i] = finalList[i]["Category"]
            toAppend = (str(i + 1) + ".").ljust(7) + finalList[i]['Title'].strip()
            s.append(toAppend)

        categories = open('c:/digitalLibrary/' + connectedUser + '/category.txt', 'w')
        for i in range(len(categoryList)):
            categories.write(",".join(categoryList[i]))
        categories.close()

Tags: intxtforcloseopencategoriessplitstrip
1条回答
网友
1楼 · 发布于 2024-09-24 12:28:26

您应该传递''.join()一个列表,而是传入一个字符串。

字符串也是序列,因此''.join()将每个字符视为单独的元素:

>>> ','.join('Hello world')
'H,e,l,l,o, ,w,o,r,l,d'
>>> ','.join(['Hello', 'world'])
'Hello,world'

相关问题 更多 >