簡體   English   中英

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

[英].split(“,”) separating every character of a string

在程序的某個點上,我要求它接受用戶的文本輸入並根據其逗號分隔文本,然后單擊",".join再次",".join",".join到txt文件中。 這個想法是要有一個列表,其中包含所有用逗號分隔的信息。

問題是,顯然,當我",".join時,它用逗號分隔每個單個字符,因此,如果我有字符串info1,info2它將分開,從而得到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()

您應該傳遞''.join()一個列表,而是傳遞一個字符串。

字符串也是序列,所以''.join()會將每個字符都視為一個單獨的元素:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM