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?
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)