파이썬
[ Python ] 정규표현식(re), 맨 마지막에 \n 없이 출력하기, 패턴 찾기
mminky
2021. 6. 14. 09:54
728x90
[ 코드 ]
import re
# 패턴 넣으면 정규표현식 이용해서 해당하는 것 리스트로 리턴(find)
def match_dna_list(pattern_s, content_s):
pattern_s_r = pattern_s.replace('_', '.')
# pattern_s_r='(?=(.A....))'
pattern_s_r = '(?=(' + pattern_s_r + '))'
find = re.findall(pattern_s_r,content_s)
#print(find)
return find
with open ('3.inp','r') as f:
#.strip()을 해줘야 \n 이 없어짐
# \n 이 있으면 완전 다른 문자가 되기 때문에 findall()하면 안 나옴
pattern = f.readline().strip()
# 나머지부분 읽음
dna_seq=''
for i in f:
dna_seq += i.strip()
with open('dna.out', 'w') as f2:
# find 안에 값이 있다면
if ( match_dna_list(pattern,dna_seq) ):
f2.write('\n'.join(match_dna_list(pattern,dna_seq)))
else:
f2.write('No')
[ 결과 ]
3.inp
_A____
CCCCCCCCCCCCCAAAATTTTTTTTGGGGGGGGGAAATTT
dna.out
----------------------------
* 정규표현식에서 모든 문자는 . 이다.
pattern_s_r = pattern_s.replace('_', '.')
* 겹치는 문자를 찾는 방법은 다음과 같다.
(?=( 패턴 )) 형식으로 만든 후 findall에 넣어준다.
pattern_s_r = '(?=(' + pattern_s_r + '))'
find = re.findall(pattern_s_r,content_s)
* 리스트로 return된 값을 '\n' 기준으로 출력하는 방법.
단, 마지막은 \n 없이 출력한다.
'\n'.join(출력원하는리스트)
print('\n'.join(match_dna_list(pattern,dna_seq)))
이때, 정수 리스트인 경우는 다음과 같이 map으로 str로 변경해준다.
list1=[1,2,3]
print('\n'.join(map(str,list1)))
반응형