code

Python-줄 바꿈으로 조인

codestyles 2020. 11. 8. 10:01
반응형

Python-줄 바꿈으로 조인


Python 콘솔에서 다음을 입력합니다.

>>> "\n".join(['I', 'would', 'expect', 'multiple', 'lines'])

제공 :

'I\nwould\nexpect\nmultiple\nlines'

이러한 결과를 기대하지만 :

I
would
expect
multiple
lines

내가 여기서 무엇을 놓치고 있습니까?


콘솔은 문자열 자체가 아니라 표현을 인쇄합니다.

접두사를 사용 print하면 예상 한 결과를 얻을 수 있습니다.

문자열과 문자열 표현의 차이점에 대한 자세한 내용은 이 질문참조하십시오 . 매우 단순화 된 표현은 해당 문자열을 얻기 위해 소스 코드에 입력하는 것입니다.


print결과를 잊었습니다 . 당신이 얻을 것은 인 P에서 RE(P)L가 아니라 실제 인쇄 결과.

Py2.x에서는 다음과 같이해야합니다.

>>> print "\n".join(['I', 'would', 'expect', 'multiple', 'lines'])
I
would
expect
multiple
lines

그리고 Py3.X에서 print는 함수이므로

print("\n".join(['I', 'would', 'expect', 'multiple', 'lines']))

이제 그것은 짧은 대답이었습니다. 실제로 REPL 인 Python 인터프리터는 항상 실제 표시되는 출력이 아닌 문자열 표현을 표시합니다. 표현은 repr진술로 얻을 수있는 것입니다 .

>>> print repr("\n".join(['I', 'would', 'expect', 'multiple', 'lines']))
'I\nwould\nexpect\nmultiple\nlines'

당신이해야 할 print그 출력을 얻을 수 있습니다.
당신은해야합니다

>>> x = "\n".join(['I', 'would', 'expect', 'multiple', 'lines'])
>>> x                   # this is the value, returned by the join() function
'I\nwould\nexpect\nmultiple\nlines'
>>> print x    # this prints your string (the type of output you want)
I
would
expect
multiple
lines

그것을 인쇄해야합니다 :

In [22]: "\n".join(['I', 'would', 'expect', 'multiple', 'lines'])
Out[22]: 'I\nwould\nexpect\nmultiple\nlines'

In [23]: print "\n".join(['I', 'would', 'expect', 'multiple', 'lines'])
I
would
expect
multiple
lines

이것을 인쇄하면 print 'I\nwould\nexpect\nmultiple\nlines'다음을 얻을 수 있습니다.

I
would
expect
multiple
lines

\n특별히 END-OF-TEXT를 표시하는 데 사용되는 새 라인 문자입니다. 줄 또는 텍스트의 끝을 나타냅니다. 이 특성은 C, C ++ 등과 같은 많은 언어에서 공유됩니다.

참고 URL : https://stackoverflow.com/questions/14560863/python-join-with-newline

반응형