1

For example:

   my_string = "hi how are you?/nIs everything ok?/nAre you happy?"

I need to make a list containing all the indexes of the newline - (/n). How can i do it ?

grael
  • 657
  • 2
  • 11
  • 26
Maya
  • 67
  • 3
  • 1
    Looks like this is addressed here: http://stackoverflow.com/questions/2294493/how-to-get-the-position-of-a-character-in-python – yano Oct 03 '15 at 20:53
  • @msw That is close, but not a great duplicate. Those solutions will all find the *first* position, not *all* positions. **Edit** I see [one answer](http://stackoverflow.com/a/32794963/2296458) at the bottom that covers this, in that case the duplicate is appropriate. – Cory Kramer Oct 03 '15 at 20:58

2 Answers2

1
import re
my_string = "hi how are you?/nIs everything ok?/nAre you happy?"
list = [m.start() for m in re.finditer('/n', my_string)]
grael
  • 657
  • 2
  • 11
  • 26
  • I think you've left in an unnecessary `(` at the start of your list comprehension: `([m.start() for m in re.finditer('/n', my_string)]` – Joe Young Oct 03 '15 at 21:00
  • @JoeYoung Indeed, a leftover from print. Thank you, fixed it. – grael Oct 03 '15 at 21:02
1

You can use enumerate in a list comprehension to create a list of indices.

>>> [index for index, value in enumerate(my_string) if value == '\n']
[15, 33]

By the way, a new line character is '\n' not '/n' (note the slash)

Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
  • Unfortunately, this provides no context to the neophyte's question who now has a working chunk in hand but no explanation of why that chunk does anything. By contrast, Bendersky's answer to the duplicate question explains that `find` is a primitive for finding within a string and provides additional explanation as to how to compose it for "all instances". Other answers in that chain augment the first answer. By contrast, Dali's answer, of which this is a dup, relies on the same accidental effect and provides no explanation, either. – msw Oct 04 '15 at 03:57