{ "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": 1, "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": 2, "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": 3, "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": [ "23\n", "spam and ham\n", " spam and ham \n", "spam and ham\n", "12\n", "\n", " spam and ham\n", "spam and ham \n", "\n", "abc\n", "abc\n" ] } ], "source": [ "u = ' spam and ham '\n", "print(len(u))\n", "print(u.strip()) # 좌우 공백을 제거하여 새로운 스트링 생성\n", "print(u) # 스트링은 변경불가능 \n", "y = u.strip() # 즉, strip()는 새로운 스트링을 생성함\n", "print(y)\n", "print(len(y))\n", "print()\n", "\n", "print(u.rstrip()) # 오른쪽 공백 제거\n", "print(u.lstrip()) # 왼쪽 공백 제거 \n", "print()\n", "\n", "print(' abc '.strip()) \n", "print('><><><>'.strip('<>')) # 인자로 주어진 스트링 안에 지정된 모든 문자를 좌우에서 제거" ] }, { "cell_type": "code", "execution_count": 5, "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": 6, "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": 8, "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", "# \n", "print(t2)\n", "print()\n", "\n", "t3 = \",\".join(t) # 리스트 t 내부의 각 원소들을 ','으로 연결한 문자열 반환\n", "print(t3)\n", "print()\n", "\n", "t4 = '\\n'.join(t) # 리스트 t 내부의 각 원소들을 '\\n'으로 연결한 문자열 반환\n", "print(t4)\n", "print()" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['스팸', '햄', '계란', '치즈']\n", "스팸 햄 계란 치즈\n" ] } ], "source": [ "#u2 = u\"스팸 햄 계란 치즈\" \n", "u2 = \"스팸 햄 계란 치즈\" # python 3 부터는 u 리터럴 표기 불필요\n", "t2 = u2.split()\n", "print(t2)\n", "print(t2[0], t2[1], t2[2], t2[3])" ] }, { "cell_type": "code", "execution_count": 10, "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)\n", "\n", "\n", "# \n", "# \n", "# ['first line', 'second line', 'third line']" ] }, { "cell_type": "code", "execution_count": 11, "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", "# \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": 13, "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": 14, "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": 15, "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": 16, "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", "|O | %s | 문자열을 포함한 임의의 객체를 문자열로 변환하여 출력 (str() 내장 함수 사용) |\n", "| | %r | 문자열을 포함한 임의의 객체를 문자열로 변환하여 출력 (repr() 내장 함수 사용) |\n", "| | %c | 1글자 문자 (ex. '%c' % 'k) |\n", "|O | %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", "|O | %f | 부동 소수점 실수 (%5.2f: 소수점 포함 총 5자리 확보한 후 2자리는 소수점 이하 자리수) |\n", "| | %g | 부동 소수점을 편의에 따라 일반 실수 형식이나 지수 형식으로 변환 |\n", "| | %G | %g와 동일 (대문자 E 표현) |" ] }, { "cell_type": "code", "execution_count": 17, "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": 18, "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": 19, "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": 20, "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": [ "### 2-3 새로운 포매팅 방법 (Python 3 기준) - 오프라인 강의 - 공부 필수\n", "- https://pyformat.info/\n", "- https://dojang.io/mod/page/view.php?id=997" ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello, world!\n", "Hello, 100\n" ] } ], "source": [ "print('Hello, {0}'.format('world!'))\n", "print('Hello, {0}'.format(100))" ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello, Python 3.6 Script\n" ] } ], "source": [ "print('Hello, {0} {2} {1}'.format('Python', 'Script', 3.6))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "![](https://dojang.io/pluginfile.php/5238/mod_page/content/1/025002.png)" ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Python Python Script Script\n" ] } ], "source": [ "print('{0} {0} {1} {1}'.format('Python', 'Script'))" ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello, Python 3.6\n" ] } ], "source": [ "print('Hello, {language} {version}'.format(language='Python', version=3.6))" ] }, { "cell_type": "code", "execution_count": 25, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " 1\n", " 1\n" ] } ], "source": [ "print('%3d' % 1)\n", "print('{0:3d}'.format(1))" ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "001\n", "001\n" ] } ], "source": [ "print('%03d' % 1)\n", "print('{0:03d}'.format(1))" ] }, { "cell_type": "code", "execution_count": 27, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "3.60\n", "3.60\n" ] } ], "source": [ "print('%.2f' % 3.6)\n", "print('{0:.2f}'.format(3.6))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 구구단 출력 포맷팅 " ] }, { "cell_type": "code", "execution_count": 28, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2 x 1 = 2\n", "2 x 2 = 4\n", "2 x 3 = 6\n", "2 x 4 = 8\n", "2 x 5 = 10\n", "2 x 6 = 12\n", "2 x 7 = 14\n", "2 x 8 = 16\n", "2 x 9 = 18\n", "\n", "3 x 1 = 3\n", "3 x 2 = 6\n", "3 x 3 = 9\n", "3 x 4 = 12\n", "3 x 5 = 15\n", "3 x 6 = 18\n", "3 x 7 = 21\n", "3 x 8 = 24\n", "3 x 9 = 27\n", "\n", "4 x 1 = 4\n", "4 x 2 = 8\n", "4 x 3 = 12\n", "4 x 4 = 16\n", "4 x 5 = 20\n", "4 x 6 = 24\n", "4 x 7 = 28\n", "4 x 8 = 32\n", "4 x 9 = 36\n", "\n", "5 x 1 = 5\n", "5 x 2 = 10\n", "5 x 3 = 15\n", "5 x 4 = 20\n", "5 x 5 = 25\n", "5 x 6 = 30\n", "5 x 7 = 35\n", "5 x 8 = 40\n", "5 x 9 = 45\n", "\n", "6 x 1 = 6\n", "6 x 2 = 12\n", "6 x 3 = 18\n", "6 x 4 = 24\n", "6 x 5 = 30\n", "6 x 6 = 36\n", "6 x 7 = 42\n", "6 x 8 = 48\n", "6 x 9 = 54\n", "\n", "7 x 1 = 7\n", "7 x 2 = 14\n", "7 x 3 = 21\n", "7 x 4 = 28\n", "7 x 5 = 35\n", "7 x 6 = 42\n", "7 x 7 = 49\n", "7 x 8 = 56\n", "7 x 9 = 63\n", "\n", "8 x 1 = 8\n", "8 x 2 = 16\n", "8 x 3 = 24\n", "8 x 4 = 32\n", "8 x 5 = 40\n", "8 x 6 = 48\n", "8 x 7 = 56\n", "8 x 8 = 64\n", "8 x 9 = 72\n", "\n", "9 x 1 = 9\n", "9 x 2 = 18\n", "9 x 3 = 27\n", "9 x 4 = 36\n", "9 x 5 = 45\n", "9 x 6 = 54\n", "9 x 7 = 63\n", "9 x 8 = 72\n", "9 x 9 = 81\n", "\n" ] } ], "source": [ "for i in range(2, 10):\n", " for j in range(1, 10):\n", " print(\"{0} x {1} = {2:2d}\".format(i, j, i*j))\n", " print()" ] }, { "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.4" } }, "nbformat": 4, "nbformat_minor": 1 }