1

Есть string

("Hello world \n
Hello with new string \n
Hello again")

Как мне удалить только первую из строк? Т.е. должно получится

"Hello with new string \n Hello again"

Пробую такой вариант, но почему-то не работает

text.split('\n')[1:]

1 ответ 1

5

Пробую такой вариант, но почему-то не работает

Это потому что, split, срезы и прочие методы строки ее не изменят в любом случае – строки в питоне неизменяемый объект. Поэтому, нужно после их применения получить результат и с ним работать.


  • А вы так попробуйте:

    text = "Hello world \n Hello with new string \n Hello again"
    text = text.split('\n')[1:]
    print(text)  # [' Hello with new string ', ' Hello again']
    
    # Обратное объединение в строку
    text = '\n'.join(text)
    print(repr(text))  # ' Hello with new string \n Hello again'
    
    # Удаление лишних "пустых" символов: '\n', ' ', '\t', и т.п.
    text = text.strip()
    print(repr(text))  # 'Hello with new string \n Hello again'
    
  • Вариант выше, но в одну строку:

    text = ' \n '.join(text.split(' \n ')[1:])
    print(repr(text))  # 'Hello with new string \n Hello again'
    
  • Используя str.partition:

    text = text.partition("\n")[2]
    print(repr(text))  # ' Hello with new string \n Hello again'
    
  • Или так:

    # Находим индекс подстроки
    i = text.find('\n ')
    text = text[i+2:]
    
    print(repr(text))  # 'Hello with new string \n Hello again'
    
  • Или регуляркой:

    import re
    text = re.search('.+?\n (.+)', text, flags=re.DOTALL)
    text = text.group(1)
    
    print(repr(text))  # 'Hello with new string \n Hello again'
    

PS. repr нужен был для отображения \n в результате

2
  • 1
    Еще вариант в коллекцию: text = text.partition("\n")[2]
    – insolor
    2 дек 2021 в 7:34
  • @insolor, спасибо! :)
    – gil9red
    2 дек 2021 в 8:13

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.