1

What is the most efficient way to delete a line from a string in python? I have tried

content = "first line \nsecond line\nthird line\netc.".splitlines()

i = 0
for line in iter(content):
  if len(line) < 5:
    content[i] = "" 
  i += 1

content = '\n'.join(content)

where my delete condition is just that the length of the line is smaller than 5 characters. Is there a more elegant/efficient way?

3 Answers 3

2

Here's a more concise one using a list comprehension:

'\n'.join([i if len(i) > 5 else '' for i in content.split('\n')])
#'first line \nsecond line\nthird line\n'

Now working from your approach... note that content is already an iterator, so there's no need for iter(content).

What else can be improved? Well instead of using a counter, python has a built-in function for that, enumerate. Using it your code could look like:

content = "first line \nsecond line\nthird line\netc."
content = content.splitlines()

for i, line in enumerate(content):
      if len(line) < 5:
            content[i] = "" 

separator = '\n'
content = separator.join(content)
Sign up to request clarification or add additional context in comments.

10 Comments

No, but join is expecting a list, so it is actually somewhat faster when fed a list rather than a gen-comp @hansolo since it will construct a list anyway
Also please comment to double check before actually modifying a post
you don't need the else '' part. [i for i in content.split('\n') if len(i) > 5] would do
@buran, you do if you want an empty line as OP had in their question.
@yatu Yep, list is faster than gen-exporession for join. Apologies
|
1

Another option is Python Regex:

import re
content = "first line \nsecond line\nthird line\netc."
print(re.sub(r'^.{1,5}$', '', content, flags=re.MULTILINE))

Resulting:

'first line \nsecond line\nthird line\n'

Comments

0

yatu's answer is nice and pythonic, but we can go further!

content = "first line \nsecond line\nthird line\netc."

content = '\n'.join(
    i if len(i) > 5 else ''
        for i in content.splitlines()
)

content
#'first line \nsecond line\nthird line'

str.join takes any iterable, so here use a generator expression for more pythonicness!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.