0

I am kinda new to python. I'm reading lines from a text file and store them in a string variable. Each line is in the following format:

text:text"text":"text":"extract":"text."text:"....

I want to delete all the characters from the string until the n'th ocurrence of the character " and save the word extract. Could someone help me on how to do this ? I'm using python3

Example:

str=text:text"text":"text":"extract":"text."text:"
someoperation(str)
print(str) #should return extract 

str arrays have different numbers of characters.

Horia
  • 9
  • 5
  • Does this help? https://stackoverflow.com/questions/509211/understanding-slice-notation – Axe319 May 07 '20 at 15:21
  • Just as a side note, the link talks about arrays, but python strings are essentially immutable arrays. This means you can't change characters in place like this. `my_str = 'some value'` `my_str[2] = 'a'`. You can however get around it by just reassigning it to the same variable like so. `my_str = 'some value'` `my_str = my_str[:2] + 'a' + my_str[3:]`. – Axe319 May 07 '20 at 15:27
  • Hello, your answer is usefull when you have the same amount of characters in the array, but my arrays have variable length, but have a fixed number of " characters so I need to extract the names from them: – Horia May 07 '20 at 15:48
  • If strings work like arrays, I think I know how to deal with this problem, with a function that searches for the character " in the string array and returns the position of it and then I just slice a number of times trough the string array. – Horia May 07 '20 at 15:57
  • strings have a useful method for that. `.find()` For example, `'test"test'.find('"')` will return `4`, the position of the `"`. – Axe319 May 07 '20 at 16:50

1 Answers1

0

You could use str.replace which accepts the number of occurrences to replace.

In [1]: s = "1-2-3-4-5-6-7-8-9"

In [2]: s.replace("-", "", 3)
Out[2]: '1234-5-6-7-8-9'

note that the replace function doesn't change the value of s, but return a new string that can be assigned to a variable. strings are immutable in python as mentioned in the comment to your post.

theFrok
  • 355
  • 1
  • 2
  • 7
  • thanks, I want to delete all the characters not only the " , but this can be implemented using find and replace. :) – Horia May 08 '20 at 06:27
  • You might want to have a look at `re.subn` which will let you replace a match of a regex with a given string – theFrok May 08 '20 at 06:58