Python/Python for Windows

[Python] 리스트의 index를 활용하여 문자열 분리

Pydole 2018. 5. 13. 01:58

리스트 객체의 index() 메소드 : 입력되는 인자 값에 해당하는 인덱스를 리턴

 

 

 

리스트의 index 메소드를 활용하여 특정 요소('log:')를 기준으로 앞부분과 뒷부분을 분리하기  


----------------------------------------------------------------------

 

예제 텍스트 파일)

 

2018-05-12 00:00:01 ABC DEFG log: this is python

2018-05-12 00:00:02 ABC DEFG HI log: this is python

2018-05-12 00:00:03 ABC DEFG HI JKL log: this is python

----------------------------------------------------------------------

 

 

with open(r'D:\Log\test.txt', 'r') as f:
    for line in f.readlines():
        log = line.split(' ')
        sep = int(log.index('log:'))
        print( ' '.join(log[:sep]),' |  ',' '.join(log[sep:]), end='')
2018-05-12 00:00:01 ABC DEFG  |   log: this is python
2018-05-12 00:00:02 ABC DEFG HI  |   log: this is python
2018-05-12 00:00:03 ABC DEFG HI JKL  |   log: this is python