Blob Blame History Raw
<?xml version="1.0" encoding="utf-8"?>
<page xmlns="http://projectmallard.org/1.0/" xmlns:its="http://www.w3.org/2005/11/its" xmlns:e="http://projectmallard.org/experimental/" type="guide" style="task" id="strings.py" xml:lang="ko">

<info>
  <title type="text">Strings (Python)</title>
  <link type="guide" xref="beginner.py#theory"/>
  <link type="next" xref="label.py"/>
  <revision version="0.1" date="2012-06-16" status="draft"/>

  <desc>파이썬과 GTK+에서 문자열을 다루는 방법을 설명합니다.</desc>
  <credit type="author copyright">
    <name>Sebastian Pölsterl</name>
    <email its:translate="no">sebp@k-d-w.org</email>
    <years>2011</years>
  </credit>
  <credit type="editor">
    <name>Marta Maria Casetti</name>
    <email its:translate="no">mmcasetti@gmail.com</email>
    <years>2012</years>
  </credit>

    <mal:credit xmlns:mal="http://projectmallard.org/1.0/" type="translator copyright">
      <mal:name>조성호</mal:name>
      <mal:email>shcho@gnome.org</mal:email>
      <mal:years>2017</mal:years>
    </mal:credit>
  </info>

<title>문자열</title>

<links type="section"/>

<note style="warning"><p>그놈은 프로그램을 작성할 때 파이썬 3 활용을 강력하게 권장합니다!</p></note>

<section id="python-2">
<title>파이썬 2의 문자열</title>

<p>파이썬 2에서는 문자열을 표현하는 두가지 다른 객체 형식이 있는데 <code>str</code>과 <code>unicode</code>가 있습니다. <code>unicode</code> 인스턴스는 유니코드 문자열을 표현할 때 활용하며, <code>str</code>형식은 인코딩한 문자열 바이트를 표현할 때 활용합니다. 내부적으로 파이썬에서는 파이썬 인터프리터를 어떻게 컴파일했느냐에 따라 유니코드 문자열을 16비트 내지는 32비트 정수로 표현합니다.</p>

<code>
&gt;&gt;&gt; unicode_string = u"Fu\u00dfb\u00e4lle"
&gt;&gt;&gt; print unicode_string
Fußbälle
</code>

<p>유니코드 문자열은 <code>unicode.encode()</code>로 8비트 문자열로 바꿀 수 있습니다. 파이썬의 8비트 문자열은 주어진 인코딩으로 문자열을 해석하는 <code>str.decode()</code> 메서드가 있습니다(그 말인 즉슨, <code>unicode.encode()</code>의 반대 개념입니다):</p>

<code>
&gt;&gt;&gt; type(unicode_string)
&lt;type 'unicode'&gt;
&gt;&gt;&gt; unicode_string.encode("utf-8")
'Fu\xc3\x9fb\xc3\xa4lle'
&gt;&gt;&gt; utf8_string = unicode_string.encode("utf-8")
&gt;&gt;&gt; type(utf8_string)
&lt;type 'str'&gt;
&gt;&gt;&gt; unicode_string == utf8_string.decode("utf-8")
True</code>

<p>불행하게도 파이썬 2.x에서는 8비트 문자열에 7비트(아스키) 바이트가 들어가지만 ASCII 값이 아닌 경우 <sys>UnicodeDecodeError</sys>가 발생하므로, <code>unicode</code>와 <code>str</code> 의 혼용을 허용하지 않습니다.</p>

</section>

<section id="python-3">
<title>파이썬 3의 문자열</title>

<p>Since Python 3.0, all strings are stored as Unicode in an instance of the <code>str</code> type. Encoded strings on the other hand are represented as binary data in the form of instances of the bytes type. Conceptually, <code>str</code> refers to text, whereas bytes refers to data. Use <code>encode()</code> to go from <code>str</code> to <code>bytes</code>, and <code>decode()</code> to go from <code>bytes</code> to <code>str</code>.</p>

<p>게다가, 더이상 유니코드 문자열과 인코딩 문자열을 혼용할 수 없는데, 결과적으로 <code>TypeError</code>가 발생하기 때문입니다:</p>

<code>
&gt;&gt;&gt; text = "Fu\u00dfb\u00e4lle"
&gt;&gt;&gt; data = b" sind rund"
&gt;&gt;&gt; text + data
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
TypeError: Can't convert 'bytes' object to str implicitly
&gt;&gt;&gt; text + data.decode("utf-8")
'Fußbälle sind rund'
&gt;&gt;&gt; text.encode("utf-8") + data
b'Fu\xc3\x9fb\xc3\xa4lle sind rund'</code>

</section>

<section id="gtk">
<title>GTK+의 유니코드</title>

<p>GTK+에서는 UTF-8 인코딩 문자열을 모든 텍스트에 사용합니다. 무슨 이야기냐면, 문자열을 반환하는 메서드를 호출하면 <code>str</code> 형식 인스턴스를 받습니다. 하나 이상의 문자열을 받는 메서드에도 동일하게 적용하며, UTF-8로 인코딩해야합니다. 그러나 PyGObject에서는 인자에 데이터가 들어오면 어떤 유니코드 인스턴스든 문자열로 자동으로 바꿔줍니다:</p>

<code>
&gt;&gt;&gt; from gi.repository import Gtk
&gt;&gt;&gt; label = Gtk.Label()
&gt;&gt;&gt; unicode_string = u"Fu\u00dfb\u00e4lle"
&gt;&gt;&gt; label.set_text(unicode_string)
&gt;&gt;&gt; txt = label.get_text()
&gt;&gt;&gt; type(txt)
&lt;type 'str'&gt;</code>

<p>게다가:</p>

<code>
&gt;&gt;&gt; txt == unicode_string</code>

<p>는 <code>False</code>값을 반환하며, <code>__main__:1: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal</code> (<code>Gtk.Label.get_text()</code> 는 항상 <code>str</code> 인스턴스를 내보내기 때문에, <code>txt</code> 와 <code>unicode_string</code> 은 다릅니다) 경고를 내보냅니다..</p>

<p><link href="http://docs.python.org/library/gettext.html"><code>gettext</code></link>로 프로그램을 국제화할 경우 특히 더 중요합니다. <code>gettext</code>에서 모든 언어에 대해 항상 UTF-8로 인코딩한 8비트 문자열을 반환하는지 확인하셔야합니다.</p>

<p>일반적으로 GTK+ 프로그램 전체에서 <code>unicode</code> 객체를 안 쓰는게 좋으며, GTK+가 <code>unicode</code>를 완전히 통합하지 않았기에,  UTF-8로 인코딩한 <code>str</code> 객체만 씁니다.</p>

<p>문자열 인코딩은 파이썬 3.x에서 좀 더 일관성이 있는데 PyGObject는 메서드로 문자열을 넘겨주거나 메서드에서 문자열을 반환할 때 자동으로 UTF-8로/부터 인코딩/디코딩을 처리합니다. 문자열, 텍스트는 항상 <code>str</code> 인스턴스로만 표현합니다.</p>

</section>

<section id="references">
<title>참고 자료</title>

<p><link href="http://python-gtk-3-tutorial.readthedocs.org/en/latest/unicode.html">문자열 다루기 - Python GTK+ 3 따라하기 지침서</link></p>

</section>

</page>