Получить все индексы пустых строк в python
Есть текст:
Put you on the rocks too, baby (Yeah) Bring you to the block too, baby (Yeah) What you want? 'Cause I want you, yeah (Oow) Ah, ah, ah, ah, ah, ah, ah, in love with you (Yeah, baby, ooh) Drop, drop, drop, drop, drop, drop, drop, yeah (Yeah, baby)
You know my buddies saying Leck, leck, leck, leck, leck, leck, leck You know my girlies saying Leck, leck, leck, leck, leck, leck, leck Ah, and everybody saying
Как получить все индексы ( если они есть ) пустых строк в тексте? Может быть возможно узнать индексы всех невидимых "/n/n" в тексте?
Ответы (2 шт):
Автор решения: Кирилл Малышев
→ Ссылка
s = '''Know you see that they been tryna be me lately I'm a heavy hitter like Gervonta Davis That shit ain't gon' save 'em, leave 'em on the pavement All I know is get this motherfuckin' paper
[Chorus: Lil Baby] Thou shall not try one of us, if they do, I'ma bust Please don't reach for no chain Not 'bout the set, but it's more 'bout respect If they get me upset, they gon' die, that's on gang
Know you see that they been tryna be me lately I'm a heavy hitter like Gervonta Davis That shit ain't gon' save 'em, leave 'em on the pavement All I know is get this motherfuckin' paper
[Chorus: Lil Baby] Thou shall not try one of us, if they do, I'ma bust Please don't reach for no chain Not 'bout the set, but it's more 'bout respect If they get me upset, they gon' die, that's on gang'''
def findall(sub, string):
index = -1
try:
while True:
index = string.index(sub, index + 1)
yield index
except ValueError:
pass
for i in findall('\n\n', s):
print(i)
Ещё можно так:
import re
res = [m.start() for m in re.finditer(r'(?=(\n\n))', s)]
Автор решения: Namerek
→ Ссылка
text = """An example using weather data provided by the API at OpenWeatherMap
Introduction
Want to know how to use PostgreSQL' s great functionality to work with JSON objects?
Novelties
Here is a concise list of the most important new features:
new datatype: json
new operators: ->, ->>, #> and #>>
new functions: json_array_length, json_extract_path, json_array_elements and many more
The full list of JSON specific functions can be found at:
https://www.postgresql.org/docs/9.3/static/functions-json.html.
General Usage of the Operators
Let’s get a quick overview concerning the main usage and differences among the three operators.
The operators -> and ->> are easy to use and allow you to point to a specific child element."""
print([a for a, b in enumerate(text.split('\n')) if not b])
# [2, 4, 6, 8, 12, 14, 17, 19]
Для файла это будет выглядеть так
file = open('example.txt', 'r', encoding='utf-8')
print([a for a, b in enumerate(file.readlines()) if b == '\n'])
file.close()
# [2, 4, 6, 8, 12, 14, 17, 19]
