【问题标题】:Move the first line of a string to the last one将字符串的第一行移到最后一行
【发布时间】:2020-09-24 10:32:21
【问题描述】:

我想将字符串的第一部分移动到该字符串的最后部分。

一个例子:

AAA
BBB
CCC

我想把它改成:

BBB
CCCAAA

我一直在寻找解决方案,但我只能看到 .readline() 仅适用于文件,不适用于变量...

【问题讨论】:

    标签: python string transform


    【解决方案1】:

    你可以分割线然后处理它们。

    example="AAA\nBBB\nCCC"
    str_lst=example.split("\n")
    to_end=str_lst.pop(0)
    str_lst.append(to_end)
    

    那么你就可以有一个这样的列表

    ['BBB', 'CCC', 'AAA']
    

    只要你喜欢就打印出来。

    【讨论】:

    • 那不是 OP 想要的输出。
    • 从长远来看,它可以帮助他操作数据,因为列表很容易操作。
    【解决方案2】:

    类似

    spam = """AAA
    BBB
    CCC"""
    
    spam = spam.splitlines()
    first = spam.pop(0)
    spam[-1] = ''.join((spam[-1],first))
    spam = '\n'.join(spam)
    print(spam)
    

    输出

    BBB
    CCCAAA
    

    替代方案:

    spam = """AAA
    BBB
    CCC"""
    
    spam = spam.splitlines()
    spam = spam[1:-1] + [''.join((spam[-1], spam.pop(0)))]
    spam = '\n'.join(spam)
    print(spam)
    

    输出:

    BBB
    CCCAAA
    

    【讨论】:

      【解决方案3】:

      首先要记住,在 Python 中字符串是不可变对象,所以你不能“移动”字符串的一部分。

      这是一个可能的解决方案:

      s='''AAA
      BBB
      CCC'''
      
      lines = s.split('\n')
      s2 = "\n".join(lines[1:]) + lines[0]
      
      print(s2)
      #BBB
      #CCCAAA
      

      【讨论】:

        【解决方案4】:

        给定

        str = """AAA
        BBB
        CCC"""
        
        split_text = str.split('\n')
        first_part = split_text[0]
        rest = split_text[1:]
        updated = "".join(rest) + first_part
        

        输出

        BBBCCCAAA
        

        【讨论】:

        • 那不是 OP 想要的输出。
        猜你喜欢
        • 1970-01-01
        • 2018-06-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-14
        • 2015-03-23
        • 2017-05-08
        • 2022-11-30
        相关资源
        最近更新 更多