0

sorry if my English is off, i am making something in python and need help with fixing a problem i have encountered. the problem im having is i need to be able to take information in a txt file up to a point signalled by a key character such as ¬, and then need to be able to take the next part of the string after the 1st ¬ to the next ¬ and so on. the reason for this is because all the strings will be of various lengths that can and will change, so if i have the string

'znPbB t7<)!\oWk_feGTIT:7{.¬ZO9?S9$v9vpd}Z#EMKC¬'

in a note pad file i need it to come out as

'znPbB t7<)!\oWk_feGTIT:7{.'

and when i want the 2nd one, it should come out as

'ZO9?S9$v9vpd}Z#EMKC'

1234USSR4321
  • 49
  • 1
  • 6
  • Possible duplicate of [How to read a file line by line into a list with Python](http://stackoverflow.com/questions/3277503/how-to-read-a-file-line-by-line-into-a-list-with-python) – jordiburgos Nov 13 '16 at 19:34

2 Answers2

0

I would use split:

s = 'znPbB t7<)!\oWk_feGTIT:7{.¬ZO9?S9$v9vpd}Z#EMKC¬'
s.split('¬')
# returns
['znPbB t7<)!\\oWk_feGTIT:7{.', 'ZO9?S9$v9vpd}Z#EMKC', '']
Wesley Bowman
  • 1,366
  • 16
  • 35
0

One solution is to split the string. Another is to use the re module. I changed the ¬ character to an ö when testing:

import re

text = 'znPbB t7<)!\oWk_feGTIT:7{.öZO9?S9$v9vpd}Z#EMKCöjndIJ%349HBhslö'
regex_result = re.findall(r"(?!ö).*?(?=ö)", text)
split_result = text.split("ö")

The difference between the results of the two is that str.split includes an empty string if the character (in my example "ö") is last.

split_result[:-1] == regex_result # <--- This is True

The regular expression can be divided into three parts. (?!ö) is a negative lookahead which excludes "ö" from the results. .*? matches anything. (?=ö) is a lookahead which tells us that "ö" is needed but not to be included in the match.

internetional
  • 312
  • 2
  • 8