문제

내 이전의 라인을 따라 질문, 값이 깔끔하게 인용되도록 문자열 목록을 문자열로 결합하려면 어떻게 해야 합니까?다음과 같은 것 :

['a', 'one "two" three', 'foo, bar', """both"'"""]

안으로:

a, 'one "two" three', "foo, bar", "both\"'"

여기에서 csv 모듈이 작동할 것으로 예상되지만 원하는 출력을 얻는 방법을 잘 모르겠습니다.

도움이 되었습니까?

해결책

사용하여 csv 모듈에서 그렇게 할 수 있습니다:

import csv
writer = csv.writer(open("some.csv", "wb"))
writer.writerow(the_list)

문자열이 필요하면 다음을 사용하십시오. StringIO 인스턴스를 파일로:

f = StringIO.StringIO()
writer = csv.writer(f)
writer.writerow(the_list)
print f.getvalue()

출력: a,"one ""two"" three","foo, bar","both""'"

csv 나중에 다시 읽을 수 있는 방식으로 쓸 것입니다.다음을 정의하여 출력을 미세 조정할 수 있습니다. dialect, 그냥 설정하세요 quotechar, escapechar, 등 필요에 따라:

class SomeDialect(csv.excel):
    delimiter = ','
    quotechar = '"'
    escapechar = "\\"
    doublequote = False
    lineterminator = '\n'
    quoting = csv.QUOTE_MINIMAL

f = cStringIO.StringIO()
writer = csv.writer(f, dialect=SomeDialect)
writer.writerow(the_list)
print f.getvalue()

출력: a,one \"two\" three,"foo, bar",both\"'

동일한 방언을 csv 모듈과 함께 사용하여 나중에 문자열을 목록으로 다시 읽을 수 있습니다.

다른 팁

관련된 메모에서 Python의 내장 인코더 문자열 이스케이프도 수행할 수 있습니다.

>>> print "that's interesting".encode('string_escape')
that\'s interesting

여기에 약간 더 간단한 대안이 있습니다.

def quote(s):
    if "'" in s or '"' in s or "," in str(s):
        return repr(s)
    return s

쉼표나 따옴표가 있을 수 있는 값만 인용하면 됩니다.

>>> x= ['a', 'one "two" three', 'foo, bar', 'both"\'']
>>> print ", ".join( map(quote,x) )
a, 'one "two" three', 'foo, bar', 'both"\''
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top