문자열

파이썬에서 다른 언어처럼 문자열이 있다.

이 문자열을 파이썬에서는 어떻게 다루는지 알아보자.

문자열 기본 예제

>>> name = 'sonic'
>>> quote = "I am 'sonic'"

>>> long_string = """This string has
... multiple lines in it"""

>>> print(name)
sonic

>>> print(quote)
I am 'sonic'

>>> print long_string
This string has
multiple lines in it

>>>

문자열의 값 다루기

파이썬은 char 타입을 지원하지 않는다.

문자열을 자를 때 대괄호( [ ] [ : ] ) 표현식과 index로 다룰 수 있다.

str1 = 'Hello Python'
str2 = 'Python Dev'

print("str1[0]: ", str1[0])
print("str2[1:5]: ", str2[1:5])

실행 결과 :

str1[0]:  H
str2[1:5]:  ytho

문자열 수정

다른 문자열을 변수에 재할당을 통해 수정을 지원한다.

str1 = 'Hello Python'

print("Update String : ", str1[:6] + 'Sonic')

실행결과 :

 Update String :  Hello Sonic

아래의 문자는 어떻게 출력할 것인가?

He said, "I am hungry"

해결

>>> print("He said, "I am hungry"")
  File "<stdin>", line 1
    print "He said, "I am hungry""
                     ^
SyntaxError: invalid syntax

>>> print("He said, \"I am hungry\"")
He said, "I am hungry"

>>> print('''He said, "I am hungry"''')
He said, "I am hungry"

>>> print("""He said, "I am hungry\"""")
He said, "I am hungry"

이스케이프 문자

백슬래시(\)로 특수문자들을 출력할 수 있다.

Escape What it does.
\ Backslash (\)
\' Single-quote (')
\" Double-quote (")
\a ASCII bell (BEL)
\b ASCII backspace (BS)
\f ASCII formfeed (FF)
\n ASCII linefeed (LF)
\r Carriage Return (CR)
\t Horizontal Tab (TAB)

문자열 연산자

문자열을 다루는 연산자를 알아본다.

Operator
+
*
[]
[ : ]
in
not in
r/R

문자열 포맷

파이썬에서는 문자열 포맷을 위한 하나의 연산자(%)를 지원한다.

print("My name is %s" % "Sonic")
print("My age is %s" % "20")
print("My age is %d" % 20)

실행결과 :

My name is Sonic
My age is 20

C 스타일

"%s %s" % ('Hello', 'World')
'Hello World'

PEP 3101 스타일

"{0} {1}".format('Hello', 'World')
'Hello World'

지원하는 포맷 기호

Format Symbol Conversion
%c character
%s string conversion via str() prior to formatting
%i signed decimal integer
%d signed decimal integer
%u unsigned decimal integer
%o octal integer
%x hexadecimal integer (lowercase letters)
%f floating point real number

키를 이용한 포매팅

>>> print('%(language)s has %(number)03d quote types.' % {"language": "Python", "number": 2})

Python has 002 quote types.

세개의 따옴표

파이썬에서는 세 개의 따옴표(""")를 이용해서 문자열을 여러 라인에 걸쳐 작성할 수 있도록 지원한다.

새 라인, 탭 또는 기타 다른 특수문자로 출력할 수 있다.

>>> para_str = """this is a long string that is made up of
several lines and non-printable characters such as
TAB ( \t ) and they will show up that way when displayed.
NEWLINEs within the string, whether explicitly given like
this within the brackets [ \n ], or just a NEWLINE within
the variable assignment will also show up.
"""

>>> print(para_str)

실행결과 :

this is a long string that is made up of
several lines and non-printable characters such as
TAB (    ) and they will show up that way when displayed.
NEWLINEs within the string, whether explicitly given like
this within the brackets [
 ], or just a NEWLINE within
the variable assignment will also show up.

이미 알다시피 백슬래시를 두번 연속 작성해야 한 개의 백슬래시가 출력된다.

>>> print('C:\\mydir')

출력결과 :

C:\mydir

r'expression' 표현식

이 표현식을 사용하면 작성하는 문자 그대로 출력 가능한다.

print(r'C:\\mydir')

실행결과 :

C:\\mydir

unicode 문자

일반적인 문자열은 8-bit ASCII로 저장된다. 유니코드 문자열은 16-bit 유니코드로 저장된다. (python 2.7 기준)

print(u'Hello Python')

실행결과 :

Hello Python

results matching ""

    No results matching ""