{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "***\n", "***\n", "# 8. 문자열 메소드와 포멧팅\n", "***\n", "***" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "***\n", "## 1 문자열 메소드(Methods)\n", "***" ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "I LIKE PROGRAMMING.\n", "i like programming.\n", "i lIKE pROGRAMMING\n", "I like programming.\n", "I Like Programming.\n" ] } ], "source": [ "s = 'i like programming.'\n", "print s.upper()\n", "print s.upper().lower()\n", "print 'I Like Programming'.swapcase() # 대문자는 소문자로, 소문자는 대문자로 변환\n", "print s.capitalize() # 첫 문자를 대문자로 변환\n", "print s.title() # 각 단어의 첫 문자를 대문자로 변환 " ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2\n", "\n", "2\n", "7\n", "7\n", "-1\n", "\n", "22\n", "-1\n" ] } ], "source": [ "s = 'i like programming, i like swimming.'\n", "print s.count('like') # 'like' 문자열이 출현한 횟수를 반환\n", "print\n", "print s.find('like') # 'like'의 첫글자 위치 (offset)를 반환\n", "print s.find('programming') # 'programming'의 첫글자 위치를 반환\n", "print s.find('programmin') # 'programmin'의 첫글자 위치를 반환\n", "print s.find('programmii') # 'programmii' 단어는 없기 때문에 -1 반환\n", "print\n", "print s.find('like', 3) # offset=3 부터 'like'을 검색하여 'like'의 첫글자 위치 반환 \n", "print s.find('my') # 'my' 단어는 없기 때문에 -1 반환" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "True\n", "False\n", "\n", "True\n", "True\n", "\n" ] } ], "source": [ "s = 'i like programming, i like swimming.'\n", "print s.startswith('i like') # 'i like'로 시작하는 문자열인지 판단\n", "print s.startswith('I like') # 대소문자 구별\n", "print\n", "\n", "print s.endswith('swimming.') # 'swimming.'로 끝나는 문자열인지 판단\n", "print s.startswith('progr', 7) # 7번째 문자열이 'progr'로 시작하는지 판단\n", "print" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "spam and ham\n", " spam and ham \n", "spam and ham\n", "\n", " spam and ham\n", "spam and ham \n", "abc\n", "abc\n" ] } ], "source": [ "u = ' spam and ham '\n", "print u.strip() # 좌우 공백을 제거하여 새로운 스트링 생성\n", "print u # 스트링은 변경불가능 \n", "y = u.strip() # strip()는 새로운 스트링을 생성함\n", "print y\n", "print\n", "\n", "print u.rstrip() # 오른쪽 공백 제거\n", "print u.lstrip() # 왼쪽 공백 제거 \n", "print ' abc '.strip() \n", "print '><><><>'.strip('<>') # 인자로 주어진 스트링 안에 지정된 모든 문자를 좌우에서 제거" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " \t abc \t \n", "abc\n" ] } ], "source": [ "p = ' \\t abc \\t '\n", "print p\n", "print p.strip() # \\t도 공백문자이므로 제거됨" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "spam, egg and ham\n", "spam and ham\n" ] } ], "source": [ "u = 'spam and ham'\n", "print u.replace('spam', 'spam, egg') # replace()는 새로운 스트링을 생성함\n", "print u" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['spam', 'and', 'ham']\n", "[' spam ', ' ham ']\n", "\n", "['spam', 'and', 'ham', 'egg', 'cheese']\n" ] } ], "source": [ "u = ' spam and ham '\n", "print u.split() # 공백으로 분리 (모든 공백 제거 및 문자열 내의 단어 리스트를 얻을 수 있음)\n", "print u.split('and') # 'and'로 분리\n", "print\n", "\n", "u2 = 'spam and ham\\tegg\\ncheese'\n", "print u2.split()" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['spam', 'ham', 'egg', 'cheese']\n", "\n", "\n", "spam:ham:egg:cheese\n", "\n", "spam,ham,egg,cheese\n", "\n", "spam\n", "ham\n", "egg\n", "cheese\n", "\n" ] } ], "source": [ "u = 'spam ham\\tegg\\ncheese'\n", "t = u.split() # 문자열 내의 단어 리스트 \n", "print t\n", "print\n", "t2 = ':'.join(t) # 리스트 t 내부의 각 원소들을 ':'로 연결한 문자열 반환\n", "print type(t2)\n", "print t2\n", "print\n", "t3 = \",\".join(t) # 리스트 t 내부의 각 원소들을 ','으로 연결한 문자열 반환\n", "print t3\n", "print\n", "t4 = '\\n'.join(t) # 리스트 t 내부의 각 원소들을 '\\n'으로 연결한 문자열 반환\n", "print t4\n", "print" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[u'\\uc2a4\\ud338', u'\\ud584', u'\\uacc4\\ub780', u'\\uce58\\uc988']\n", "스팸 햄 계란 치즈\n" ] } ], "source": [ "u2 = u\"스팸 햄 계란 치즈\"\n", "t2 = u2.split()\n", "print t2\n", "print t2[0], t2[1], t2[2], t2[3]" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "\n", "['first line', 'second line', 'third line']\n" ] } ], "source": [ "lines = '''first line\n", "second line\n", "third line'''\n", "print type(lines)\n", "lines2 = lines.splitlines() # 문자열을 라인 단위로 분리한 각 원소들을 지닌 리스트 반환\n", "print type(lines2)\n", "print lines2" ] }, { "cell_type": "code", "execution_count": 34, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", " spam and egg \n", "spam and egg \n", " spam and egg\n" ] } ], "source": [ "u = 'spam and egg'\n", "c = u.center(60) # 60자리를 확보하되 기존 문자열을 가운데 정렬한 새로운 문자열 반환\n", "print type(c)\n", "print c\n", "print u.ljust(60) # 60자리를 확보하되 기존 문자열을 왼쪽 정렬한 새로운 문자열 반환\n", "print u.rjust(60) # 60자리를 확보하되 기존 문자열을 오른쪽 정렬한 새로운 문자열 반환" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "------------------------spam and egg------------------------\n", "spam and egg------------------------------------------------\n", "------------------------------------------------spam and egg\n" ] } ], "source": [ "u = 'spam and egg'\n", "print u.center(60, '-') # 공백에 채워질 문자를 선택할 수 있음\n", "print u.ljust(60, '-')\n", "print u.rjust(60, '-')" ] }, { "cell_type": "code", "execution_count": 42, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "True\n", "True\n", "True\n", "True\n", "True\n", "True\n", "True\n" ] } ], "source": [ "print '1234'.isdigit() # 문자열 내의 Character들이 모두 숫자인가?\n", "print 'abcd'.isalpha() # 문자열 내의 Character들이 모두 영문자인가?\n", "print '1abc234'.isalnum() # 문자열 내의 Character들이 모두 영문자 또는 숫자인가? \n", "print 'abc'.islower() # 문자열 내의 Character들이 모두 소문자인가?\n", "print 'ABC'.isupper() # 문자열 내의 Character들이 모두 대문자인가?\n", "print '\\t\\r\\n'.isspace() # 문자열 내의 Character들이 모두 공백 문자인가?\n", "print 'This Is A Title'.istitle() # 문자열이 Title 형식 (각 단어의 첫글자가 대문자)인가?" ] }, { "cell_type": "code", "execution_count": 45, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "00123\n", "0goofy\n" ] } ], "source": [ "s = '123'\n", "print s.zfill(5) # 5글자 자리 확보뒤 문자열을 쓰되 남는 공백에는 zero (0)를 채움 \n", "print 'goofy'.zfill(6) # 6글자 자리 확보뒤 ..." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "***\n", "## 2 문자열 포매팅\n", "***" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 2-1 튜플을 이용한 포매팅" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### 1) 문자열 변환" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 포맷팅 문자\n", " - 문자열 내에 존재하는 %\n", "- 포캣팅을 활용한 문자열 변환\n", " - 포맷팅 문자를 포함하는 문자열 % 튜플" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "name = gslee, age = 24\n" ] } ], "source": [ "print 'name = %s, age = %s' % ('gslee', '24')" ] }, { "cell_type": "code", "execution_count": 27, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "안녕하세요 홍길동님,\n", "\n", "오늘 밤 파티에 참석해 주실 수 있나요?\n", "\n", "그럼..\n", "\n", "이강성 드림\n", "\n", "\n", "안녕하세요 한학신님,\n", "\n", "오늘 밤 파티에 참석해 주실 수 있나요?\n", "\n", "그럼..\n", "\n", "이강성 드림\n", "----------------------------------------\n", "\n", "\n", "안녕하세요 정인숙님,\n", "\n", "오늘 밤 파티에 참석해 주실 수 있나요?\n", "\n", "그럼..\n", "\n", "이강성 드림\n", "----------------------------------------\n", "\n", "\n", "안녕하세요 박미경님,\n", "\n", "오늘 밤 파티에 참석해 주실 수 있나요?\n", "\n", "그럼..\n", "\n", "이강성 드림\n", "----------------------------------------\n", "\n" ] } ], "source": [ "letter = '''\n", "안녕하세요 %s님,\n", "\n", "오늘 밤 파티에 참석해 주실 수 있나요?\n", "\n", "그럼..\n", "\n", "이강성 드림'''\n", "name = '홍길동'\n", "print letter % name\n", "print \n", "names = ['한학신', '정인숙', '박미경']\n", "for name in names:\n", " print letter % name\n", " print '-' * 40\n", " print" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### 2) 포맷팅 문자" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "| 포맷팅 문자 | 설명 |\n", "|-------------|------------------------------------------------------------------------------|\n", "| %s | 문자열을 포함한 임의의 객체를 문자열로 변환하여 출력 (str() 내장 함수 사용) |\n", "| %r | 문자열을 포함한 임의의 객체를 문자열로 변환하여 출력 (repr() 내장 함수 사용) |\n", "| %c | 1글자 문자 (ex. '%c' % 'k) |\n", "| %d | 10진 정수 (%5d: 5자리를 확보한 후 정수 포맷팅) |\n", "| %i | %d와 동일 |\n", "| %u | 부호 없는 정수. 음수는 양수처럼 해석함 (ex. '%u' % -12 --> '4294967284') |\n", "| %o | 8진수 정수 (ex. '%o' % 13 --> 15) |\n", "| %x | 16진수 정수 (소문자 표현) (ex. '%x' % 13 --> 'd') |\n", "| %X | 16진수 정수 (대문자 표현) (ex. '%X' % 13 --> 'D') |\n", "| %e | 부동 소수점 실수를 지수 형태로 표현 (%.2e: 2자리는 소수점 이하 자리수) |\n", "| %E | %e 와 동일 (대문자 E 표현) |\n", "| %f | 부동 소수점 실수 (%5.2f: 소수점 포함 총 5자리 확보한 후 2자리는 소수점 이하 자리수) |\n", "| %g | 부동 소수점을 편의에 따라 일반 실수 형식이나 지수 형식으로 변환 |\n", "| %G | %g와 동일 (대문자 E 표현) |" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "(1, 2) -- [3, 4, 5] -- 5 -- 5.300000 -- 1.013000e+02\n" ] } ], "source": [ "print \"%s -- %s -- %d -- %f -- %e\" % ((1, 2), [3,4,5], 5, 5.3, 101.3)" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " 5 -- 5.36 -- 1.01e+02\n" ] } ], "source": [ "print \"%3d -- %5.2f -- %.2e\" % (5, 5.356, 101.3)" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "456 -- 710 -- 1c8 -- 1C8\n" ] } ], "source": [ "a = 456\n", "print '%d -- %o -- %x -- %X' % (a, a, a, a)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 2-2 사전(Dictionary)을 이용한 포매팅" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "홍길동 -- 5284\n", "홍길동 -- 5284\n", "홍길동 -- 5284\n" ] } ], "source": [ "print '%(이름)s -- %(전화번호)s' %{'이름':'홍길동', '전화번호':5284}\n", "print '%(이름)s -- %(전화번호)s' %{'전화번호':5284, '이름':'홍길동'}\n", "print '%(이름)s -- %(전화번호)s' %{'전화번호':5284, '이름':'홍길동', '주소':'Seoul'}" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "

참고 문헌: 파이썬(열혈강의)(개정판 VER.2), 이강성, FreeLec, 2005년 8월 29일

" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.6.1" } }, "nbformat": 4, "nbformat_minor": 1 }