를이 (정규식 사용) 시도하며 @ unutbu 년대보다 짧다 해결책.
루프 홀이 있는데, #
이 포함 된 문자열은 이와 함께 작동하지 않습니다.
import re
scode = '''print "'Hello World'" # prints 'Hello World'
u'Unicode is unchanged'
# so are "comments"
'#### Hi' # 'Hi' '''
x1 = re.compile('''(?P<unicode>u?)(?P<c>'|")(?P<data>.*?)(?P=c)''')
def in_string(text,index):
curr,in_l,in_str,level = '',0,False,[]
for c in text[:index+1]:
if c == '"' or c == "'":
if in_str and curr == c:
instr = False
curr = ''
in_l -= 1
else:
instr = True
curr = c
in_l += 1
level.append(in_l)
return bool(level[index])
def repl(m):
return "u%(c)s%(data)s%(c)s" % m.groupdict()
def handle_hashes(i):
if i.count('#') == 1:
n = i.find('#')
else:
n = get_hash_out_of_string(i)
return re.sub(x1,repl,i[:n]) + i[n:]
def get_hash_out_of_string(i):
n = i.find('#')
curr = i[:]
last = (len(i)-1)-''.join(list(reversed(i))).find('#')
while in_string(curr,n) and n < last:
curr = curr[:n]+' '+curr[n+1:]
n = curr.find('#')
return n
fcode = '\n'.join(
[re.sub(x1,repl,i)
if not '#' in i
else handle_hashes(i)
for i in scode.splitlines()])
print fcode
출력 :
print u"'Hello World'" # prints 'Hello World'
u'Unicode is unchanged'
# so are "comments"
u'#### Hi' # 'Hi'
W |
출력은 :
#
를 들어나는 (그리고 더 이상 @ unutbu의 솔루션에 비해입니다)이 있습니다 하이 "u"결과 코드 % d "'? – unutbu
당신은 항상 파이썬 3을 사용할 수 있습니다 :) – MattDMo
@unutbu 당신은 절대적으로 옳습니다. 나는 그것을 포함시키기 위해 질문을 편집했다. 바보 나. – mmopy