如何在Python中将列表转换为字符串?

时间:2018-03-20 00:56:50

标签: python string python-3.x list

我想转换以下内容的结果:

def main():
    list = open('friends.txt').readlines()
    list.sort()
    f = open('friends_sorted.txt', 'w+')
    f.write(str(list))
    f.close()

if __name__ == '__main__':
    main()

[' David \ n',' Geri \ n',' Jessica \ n',' Joe \ n',&# 39; John \ n',' Rose \ n']

大卫
杰瑞
杰西卡

约翰
玫瑰

-

我该怎么做?

1 个答案:

答案 0 :(得分:0)

这假设您的源数据位于文件中并且看起来/格式化为列表,但实际上并非如此。当您打开文件并开始处理它时,它将是一个字符串。因此,考虑到这一点,需要完成其他任务,主要是剥离不需要的东西。就个人而言,我认为您需要更好地格式化源文件,以便减少工作量。但是这里......

这是数据在名为' friends.txt'

的文件中的显示方式
['David\n', 'Geri\n', 'Jessica\n', 'Joe\n', 'John\n', 'Rose\n']

#!python3

def main():
    s1 = ''; s2 = '' # strings to hold data being processed

    new_friends = [] # this will hold your new and exciting friends, but
                     # without the baggage of square brackets, quotes,
                     # new lines, or commas that are part of the string

    # use with open(), no closing of file required;
    # 'fp' stands for 'file pointer', call it whatever you want to call it;
    # all of the data in any file that gets opened up in this way is
    # always a string, it doesn't matter how it's formatted in the file
    with open('friends.txt', 'r') as fp:
        for line in fp:
            # strip out square brackets, quotes, and strings that look like
            # new lines but aren't new lines; split the statement over
            # 2 lines using a trailing backslash, doing so allows for easier
            # reading of the statement without excessive scrolling
            s1 = line.replace('[', '').replace(']', '') \
            .replace("'", '').replace('\\n', '')

        # strip out trailing new line
        s1 = s1.rstrip()

        # split() returns a list, split string on a 'comma/space'
        new_friends = s1.split(', ')

    # sort list, print results, build string that will be written to file
    for item in sorted(new_friends):
        print(item)        # print results
        s2 += item + '\n'  # build string

    # write to new file;
    # 'wf' stands for 'write file', call it whatever you want to call it
    with open('new_freinds.txt', 'w') as wf:
        wf.write(s2)

# start the program
if __name__ == '__main__':
    main()