Read characters of line and return positions - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Read characters of line and return positions (/thread-30752.html) |
Read characters of line and return positions - Gizzmo28 - Nov-04-2020 Hello, I am trying to pull out certain information from a huge text file because the lines are difficult to read. I can read line by line but how do I put each character in a list or array to pull out characters at certain positions? Do I use split or strip? Here is an example of a line: 0000009887465 000002250000000000089877000000000000.0002/28/202000000000.00000000000.00 I need to pull position 6 thru 13 and to get: 9887465 Then pull 27 thru 30 and 61 thru 71 to get: 225 02/28/2020 So the output would be 9887465 225 02/28/2020 If someone could point me in the right direction. Thanks! ps. there is supposed to 9 white spaces after 65 RE: Read characters of line and return positions - deanhystad - Nov-04-2020 Slice long_str = '0000009887465 000002250000000000089877000000000000.0002/28/202000000000.00000000000.00' print(long_str[6:13]) print(long_str[19:22]) print(long_str[53:63])
RE: Read characters of line and return positions - perfringo - Nov-04-2020 Iterating on deanhystad solution. It's more lines of code but presumably if you return to it in couple of weeks this makes much easier to remember what it's all about. data = "0000009887465 000002250000000000089877000000000000.0002/28/202000000000.00000000000.00" first_ID = slice(6, 13) second_ID = slice(19, 22) date = slice(53, 63) extracted = f'{data[first_ID]} {data[second_ID]} {data[date]}' print(extracted) -> 9887465 225 02/28/2020 |