회원 로그인
정보기억 정보기억에 체크할 경우 다음접속시 아이디와 패스워드를 입력하지 않으셔도 됩니다.
그러나, 개인PC가 아닐 경우 타인이 로그인할 수 있습니다.
PC를 여러사람이 사용하는 공공장소에서는 체크하지 마세요.
소셜네트워크 서비스를 통해서 로그인하시면 별도의 로그인 절차없이 회원서비스를 이용하실 수 있습니다.


최근 게시물

1.노션에서 작성 중

1.노션에서 작성 중

개편하기 전까지 노션에서 작성 중

2024.04.04//read more

2.ChatGPT

2.ChatGPT

OpenAI로 대규모 언어 모델대화형...

2023.03.16//read more

3.노코딩 게임 엔진 - 빌..

3.노코딩 게임 엔진 - 빌..

빌드 지원안드로이드iOS윈도우즈특이사...

2023.03.14//read more

4.(완료) 미접속 회원 정..

4.(완료) 미접속 회원 정..

[완료] 36명의 회원을 정리하였습니...

2023.02.16//read more

5.매뉴얼 플러스 - 전자제..



안정적인 DNS 서비스 DNSEver
DNS Powered by DNSEver.com


Python 4강 - 문자열

artsone | 2007.10.20 03:04 | 조회 3700
Python04-1.asf

Python 4강

문자열

1. 시퀀스 자료형의 특성
2. 문자열 정의하기
3. 문자열 변경하기
4. 포매팅
5. 문자열 메쏘드
6. string 모듈
7. 유니코드
8. 문서문자열



1. 시퀀스 자료형의 특성
시퀀스 자료형이란?
여러 객체를 저장
각 객체들은 순서를 갖는다
각 객체들은 첨자를 이용하여 참조가능 하다
종류
리스트, 튜플, 문자열
공동 연산
인덱싱(indexing) [1]
슬라이싱(slicing) [1:4]
연결하기 s + t
반복하기 s * 4
멤버십 테스트 'a' in s
길이 정보 len(s)

>>> s = 'spam and ham' #s 변수에 문자열 입력
>>> s[0] #s의 0번째 출력(인덱싱)
's'
>>> s[1]
'p'
>>> s[-1] #s의 뒤에서 첫번째 출력(인덱싱)
'm'
>>> s[-2] #s의 뒤에서 두번째 출력(인덱싱)
'a'
>>> s[1:4] #s의 1에서 4번째 출력(슬라이싱)
'pam' #[1:4] 앞뒤 생략하면 처음부터[1:], 끝까지[:4]
>>> s + s #연결하기
'spam and hamspam and ham'
>>> s * 3 #반복하기
'spam and hamspam and hamspam and ham'
>>> 'a' in s #s안에 a라는 문자가 있는지
True #참이면 True, 1
>>> 'z' in s
False #거짓이면 False, 0
>>> len(s) #s의 문자 길이 출력
12



2. 문자열 정의하기
#한 줄 문자열
'혹은 "로 묶어서 정의


>>> s = ''
>>> str1 = 'Python is Great!'
>>> str2 = 'That's good' #문자열에 '가 있을 시
SyntaxError: invalid syntax
>>> str2 = "Taht's good" #"로 묶어 사용가능
>>> str6 = "tdsaf "dfda" #"안에 "는 사용 불가능 하나
SyntaxError: invalid syntax
>>> str4 = "Don"t walk" #앞에 를 붙여 사용 가능하게 할수 있다.
>>> long_str = 'Long line #긴 문자열일 경우 마지막에 (라인 연속 표시)를 사용
contined..' #문자열을 계속 이어 주면 된다.
>>> long_str
'Long linecontined..'


#여러 줄 문자열
'''혹은 """로 정의

>>> multiple_lines = ''' #(엔터)
first line
second line
third line #(엔터)
'''
>>> print multiple_lines
#위
first line
second line
third line
#아래

위 아래 공간이 생기는 이유는 변수 정의 할때 엔터를 쳤기 때문이다.

>>> multiple_lines = '''first line
second line
third line'''
>>> print multiple_lines
first line
second line
third line

엔터 없이 문자열 정의할때 위 같이 하면 공간이 생기지 않는다.


#이스케이프 문자
키보드로 표현하기 힘든 코드 표현
python4-1.jpg

문자 의미
Enter 라인연속
문자
' ' 문자
" " 문자
b 백스페이스
n 또는 12 줄바꾸기
t 탭
xx 8진 코드 xx
xXX 16진 코드 XX
e Ese 키


>>> print 'anb12c' #n, 12 줄바꾸기
a
b
c


3. 문자열 변경하기
#직접적인 변경은 불가
#새로운 이름으로 치환


>>> s = 'spam and egg'
>>> s = s[:5] + 'cheese ' + s[5:] #변수 s를 다시 치환
>>> s
'spam cheese and egg'



4. 포매팅
#문자열을 자유롭게 구성할 수 있는 방법
#양식과 데이터를 분리


>>> s = 'spam and egg'
>>> names = ['artsOne', 'dvframes']
>>> for name in names:
print '%s님 안녕하세요' % name #%name이 %s에 들어가게 된다.


artsOne님 안녕하세요
dvframes님 안녕하세요


#기타 다른 자료의 변환
>>> "%3d -- %5.3f -- %.2e" %(5, 5.356, 101.3) #(5, 5.356, 101.3) 튜플 데이터가 앞 " "(또는 ' ') 안에 있는 데이터와 자료형에 맞게 치환된다.
' 5 -- 5.356 -- 1.01e+002'
>>> '%s -- %s' % ([1,2,3], (1,2,3)) #리스트와 튜플, 어떠한 자료형도 문자로 치환한다.
'[1, 2, 3] -- (1, 2, 3)'

>>> a = 456
>>> '%d -- %f -- %o -- %x -- %X' %(a, a, a, a, a) #자료형에 맞게 치환된다.
'456 -- 456.000000 -- 710 -- 1c8 -- 1C8'

%d 정수
%f 실수
%o 8진수 (01234567)
%x 16진수 소문자 (0123456789abcdef)
%X 16진수 대문자 (0123456789ABCDEF)

위 예제인 %3d는 정수의 최소 자리수
>>> '%3d' % 1
' 1'
>>> '%3d' % 12345
'12345'

%5.2f는 총 5자리 중 2자리는 소수점 이하
>>> '%5.2f' % 5.356
' 5.36' #반올림

%.2e는 지수
>>> '%.2e' % 00101.3
'1.01e+002'

지수의 이해
0이 아닌 첫 숫자.2자리 소수점e+소수점의 이동수
위 예제 101.3
첫숫자 1
2자리 소수점 01e
101.3와 1.01e의 소수점 이동수 2 (10의 +2승)
그러므로 1.01e+002가 나온다.



Python04-1.asf 13:30

#사전을 이용한 포매팅
사전은 순서에 구애받지 않고, 위치나 횟수에 상관 없이 출력
{키:벨류}로 구성

>>> print '%(이름)s -- %(전화번호)s' % {'이름':'artsOne', '전화번호':1234}
artsOne -- 1234
>>> d = {'name':'artsOne', 'phone':1234}
>>> print '%(name)s 어쩌구 %(name)s %(phone)s %(name)s' % d
artsOne 어쩌구 artsOne 1234 artsOne


#변수 포매팅

>>> name = 'artsOne' #새 변수 정의
>>> vars() #지역 변수의 사전을 넘긴다.
{'__builtins__': , '__name__': '__main__', '__doc__': None, 'd': {'phone': 1234, 'name': 'artsOne'}, 'name': 'artsOne'}
사전에 보면 {'phone': 1234, 'name': 'artsOne'}이 vars() 함수에 정의 된걸 알 수 있다.
>>> name = 'artsOne' #새 변수 정의
>>> phone = 1234
>>> '%(name)s -- %(phone)s' % vars() #vars()에 정의 되어 있으므로 바로 vars()만으로도 사전을 출력할 수 있게 된다.
'artsOne -- 1234'


Python04-1.asf 끝

Python04-2.asf

5. 문자열 메쏘드
#대소문자 변환
upper(), lower() - 대소문자 변환
capitalize() - 첫 문자를 대문자로
검색 관련
count(s) - 문자열 s가 몇 번 발생?
find(s), rfind(s) - s위치, 없으면 -1
index(s) - s위치, 없으면 예외
ValueError 발생

문자열은 하나의 객체
객체에 속한 함수를 메쏘드라 한다.

>>> s = 'spam and ham'
>>> s.upper() #변수.함수() = 메쏘드
'SPAM AND HAM' #대문자로 변경되었다.
>>> s.upper().lower() #다시 메쏘드 구성 가능, 다시 소문자로 변경
'spam and ham'
>>> s.capitalize() #첫번째 문자를 대문자로 변경
'Spam and ham'

>>> s.count('a') #문자열 안에 a가 몇번 들어가는지
3
>>> s.find('and') #문자열 앞에서 and가 몇번째 있는지
5
>>> s.rfind('m') #문자열 m 위치를 뒤에서 부터 찾는다.
11
>>> s.find('m', 2) #시작 위치를 정할 수 있다. 문자열 2번째 부터 m를 찾는다.
3
>>> s.rfind('m', -2) #-2면 뒤에서 부터 두번째 문자열에서부터 m를 찾게 된다.
11

>>> s.find('egg') #find() 메쏘드에서 egg가 없으면 -1을 출력하는데
-1
>>> s.index('egg') #index() 메쏘드는 ValueError를 표시한다.

Traceback (most recent call last):
File "", line 1, in
s.index('egg')
ValueError: substring not found

오류 처리를 할경우 try를 활용한다.
예)
>>> try:
k = s.index('egg')
except ValueError: #ValueError가 발생할 경우 아래 명령을 출력하게 된다.
print 'egg not found'


egg not found



06:00
#편집 및 치환
strip(), lstrip(), rstrip() - 좌우 공백 없앰
replace(a, b) - a를 b로 바꾼다
expandtabs() - 탭을 공백 문자로 바꾼다

>>> t = ' spam '
>>> t.lstrip() #왼쪽 공백을 없앤다.
'spam '
>>> t.rstrip() #오른쪽 공백을 없앤다.
' spam'
>>> t.strip() #양쪽 공백을 없앤다.
'spam'

>>> s = 'spam and ham'
>>> s.replace('and', 'or') #문자열 and를 or로 변경한다.
'spam or ham'

>>> t = 'atbtc' #탭 이스케이프 문자를 넣고
>>> t
'atbtc'
>>> print t #공간이 탭으로 출력된다.
a b c
>>> t2 = t.expandtabs() #expandtas() 메쏘드를 사용하여
>>> t2
'a b c' #탭을 띄어쓰기 빈공간으로 변경한다.
>>> print t2
a b c
>>> t2 = t.expandtabs(4) #expandtas(n) 함수 안에 값(n)을 넣어 탭간격을 정의할 수 있다.
>>> print t2
a b c

#분리와 결합 (많이 사용되는 메쏘드)
split() - 문자열 분리
join() - 문자열 결합


>>> s = 'spam and ham'
>>> s.split('and') #and 기준으로 좌우가 분리
['spam ', ' ham']
>>> s
'spam and ham'
>>> mul = '''line1 #문자열이 여러개의 라인으로 가지고 있을 때
line2
line3'''
>>> mul.split('n') #n라인 단위로 저장되어 문자열을 리스트로 활용 가능하다.
['line1', 'line2', 'line3']
>>> for line in mul.split('n'):
print line, len(line) #


line1 6
line2 5
line3 5

>>> s = 'spam and ham'
>>> t = s.split() #문자열을 리스트로 정의하고
>>> t
['spam', 'and', 'ham']
>>> ''.join(t) #문자열 사이에 공백을 없애거나
'spamandham'
>>> ' '.join(t) #공백을 넣어 결합할 수 있다.
'spam and ham'
>>> 'n'.join(t)
'spamnandnham'
>>> print 'n'.join(t) #또한 이스케이프 문자를 넣어 활용하거나
spam
and
ham
>>> print ':'.join(t) #문자열을 넣을 수 있다.
spam:and:ham
>>> print '^^^'.join(t)
spam^^^and^^^ham


#정렬(alignment)
center(), ljust(), rjust()

>>> s = 'spam and ham'
>>> s.center(30) #총 30의 문자 길이를 가지면서 가운대 정렬
' spam and ham '
>>> s.ljust(30) #30 문자 길이중 왼쪽부터 정렬
'spam and ham '
>>> s.rjust(30) #30 문자 길이중 오른쪽부터 정렬
' spam and ham'


Python04-2.asf 12:30
#문자열 질의
isalnum(), isalpha(), isdigit(), islower(), isspace(), istitle(), isupper()
영문자숫자, 영문자, 숫자, 소문자, 스페이스문자, 제목문자, 대문자

>>> s = 'spam and ham'
>>> s.istitle() #문자열이 대문자 제목이 아니라서 False
False
>>> 'Gone with the wind'.istitle() #마찮가지
False
>>> 'Gone With The Wind'.istitle() #문자열 앞에 대문자 제목이라 true
True
>>> 'fadsfa1334'.isalnum() #영문자숫자 이므로 true
True
>>> '12321'.isdigit() #숫자라 true
True

#예제 1: 문자열 붙이기1
>>> s = '' #문자열 붙이기
>>> for k in range(10):
s += 'spam'

>>> print s
spamspamspamspamspamspamspamspamspamspam


#예제 1: 문자열 붙이기2
>>> t = [] #리스트로 이용한 문자열 붙이기
>>> for k in range(10):
t.append('spam')

>>> s = ''.join(t)
>>> print t
['spam', 'spam', 'spam', 'spam', 'spam', 'spam', 'spam', 'spam', 'spam', 'spam']

예제1은 문자열에 순서대로 저장되기 때문에 range()의 길이가 커지게 되면 결과까지 오랜 시간이 걸리게 된다.
그걸 보안해서 예제2와 같이 리스트를 사용하여 연산 시간을 단축 시킬수 있으므로 꼭 기억해 두자.



6. string 모듈
#모듈 상수
digits, octdigits, hexdigits, letters, lowercase, uppercase, punctuation, printable, whitespace
>>> import string #string 모듈을 사용하기 위해서 임포트
>>> string.digits #10진수
'0123456789'
>>> string.octdigits #8진수
'01234567'
>>> string.hexdigits #16진수
'0123456789abcdefABCDEF'
>>> string.letters #대소영문자
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
>>> string.lowercase #영소문자
'abcdefghijklmnopqrstuvwxyz'
>>> string.uppercase #영대문자
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> string.punctuation #기호 문자
'!"#$%&'()*+,-./:;<=>?@[]^_`{|}~'
>>> string.printable #출력가능한 문자
'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&'()*+,-./:;<=>?@[]^_`{|}~ tnrx0bx0c'
>>> string.whitespace
'tnx0bx0cr ' #공백문자(이스케이프 문자)


>>> s = '123'
>>> for ch in s:
if ch in string.digits:
print '%s is in digits' % ch


1 is in digits
2 is in digits
3 is in digits
>>> string.digits + string.letters #string 모듈 연결 가능
'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
>>> string.digits + string.letters + '_' #문자열 연결도 가능
'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_'

>>> s = 'spam'
>>> string.upper(s) #문자열을 대문자로 출력
'SPAM'
>>> s.upper() #마찮가지로 출력하는데 이 출력방법을 추천한다.
'SPAM'


#모듈 함수
대부분은 문자열 메쏘드와 동일
capwords(s) - 각 단어의 첫 문자를 대문자로
zfille(s, n) - 왼쪽의 빈자리를 0으로 채운다

>>> string.capwords('spam and ham') #첫 문자를 대문자로
'Spam And Ham'
>>> string.zfill('123', 6) #총 6공간을 문자열의 빈공간을 0으로 채워준다.
'000123'



7. 유니코드(v1.8부터 도입)
http://sourceforge.net/projects/koco
KoreanCodecs-2.0.2.win32-py2.2.exe

>>> print u'Spam and Egg' #문자를 유니코드화 한다.
Spam and Egg
>>> print u'Spam uB610 Egg' #uB610은 한글 또 라는 유니코드
Spam 또 Egg
>>> unicode('한글') #유니코드 출력
u'ud55cuae00'
>>> unicode('한글').encode('euc-kr') #encode() 케릭터셋을 이용한 변환
'xc7xd1xb1xdb'
>>> unicode('한글').encode('utf-8')
'xedx95x9cxeaxb8x80'
>>> len(unicode('한글')) #유니코드로 변환한 길이도 출력 가능
2


8. 문서문자열
주석을 표현하기 위한 문서 문자열
#(코맨트)가 아닌 모듈, 함수, 메쏘드 해설 가능

#모듈이나 함수, 메쏘드를 해설하는 문서 문자열
#문서 문자열의 참조
__doc__ 객체 속성
좀 더 자세한 설명을 보려면 help를 이용
형식화해서 표시
하위 함수나 클래스의 문서 문자열도 표시
#문서 문자열 만들기
모듈 - 파일의 첫 문자열
함수 - 함수의 첫 문자열
클래스, 메쏘드.. 등도 마찮가지임

>>> import string
>>> string.upper

>>> string.upper.__doc__ #string의 upper()함수 참조할 수 있다.
'upper(s) -> stringnn Return a copy of the string s converted to uppercase.nn '
>>> print string.upper.__doc__ #string의 upper()함수 사용법이 나온다.
upper(s) -> string

Return a copy of the string s converted to uppercase.

>>> print string.__doc__ #string 모듈에 관한 설명을 볼 수 있다.
A collection of string operations (most are no longer used).

Warning: most of the code you see here isn't normally used nowadays.
Beginning with Python 1.6, many of these functions are implemented as
methods on the standard string object. They used to be implemented by
a built-in module called strop, but strop is now obsolete itself.

Public module variables:

whitespace -- a string containing all characters considered whitespace
lowercase -- a string containing all characters considered lowercase letters
uppercase -- a string containing all characters considered uppercase letters
letters -- a string containing all characters considered letters
digits -- a string containing all characters considered decimal digits
hexdigits -- a string containing all characters considered hexadecimal digits
octdigits -- a string containing all characters considered octal digits
punctuation -- a string containing all characters considered punctuation
printable -- a string containing all characters considered printable

File > Open Modul..을 클릭 하여 sting을 검색하면
처음 나오는 문자열이 바로 위 내용과 같다.

다른 항목의 자세히 보려면 help()함수를 쓰면 된다.
>>> help(sting.upper)
Help on function upper in module string:

upper(s)
upper(s) -> string

Return a copy of the string s converted to uppercase.


Python04-2.asf 끝
285개(14/15페이지)
프로그래밍
번호 제목 글쓴이 조회 날짜
25 [VisualStudio] Visual Studio Express 2012 다운로드/설치 첨부파일 푸딩뱃살 2731 2013.04.06 20:12
24 [Python] DC 이효리 겔러리에서 사진 추출하기 사진 artsOne 934 2009.03.27 01:54
23 [Python] 클래스 안의 함수 실행 artsOne 2546 2012.09.20 11:54
22 [Python] 기본 함수들 artsOne 4882 2012.09.12 15:39
21 [Python] Config Parser artsOne 2265 2012.08.28 13:55
20 [Python] win32 오픈오피스 실행 artsOne 2154 2012.08.01 17:38
19 [Python] 문자열의 기호들을 출력하기 artsOne 2868 2009.04.17 11:59
18 [Python] python 자료형 / 자료형 출력 artsOne 3394 2009.03.30 00:54
17 [Python] win32 모듈로 Excel 사용하기 artsOne 4113 2008.03.18 02:24
16 [Python] 용어 정리 artsone 3565 2008.02.26 23:11
15 [Python] Python 9강 - 파일 사진 첨부파일 artsone 9963 2007.11.03 02:59
14 [Python] Python 8강 - 객체의 복사 및 형 변환 사진 첨부파일 artsone 5220 2007.11.01 04:15
13 [Python] Python 7강 - 사전 사진 첨부파일 artsone 2871 2007.10.30 03:26
12 [Python] Python 6강 - 튜플 artsone 3139 2007.10.24 05:30
11 [Python] Python 5강 - 리스트 사진 첨부파일 artsone 7338 2007.10.23 22:13
>> [Python] Python 4강 - 문자열 사진 첨부파일 artsone 3701 2007.10.20 03:04
9 [Python] Python 3강 - 수치 자료형과 연산자 사진 첨부파일 artsone 4197 2007.10.18 17:01
8 [Python] Python 2강 - 파이썬 문과 기본 자료형 사진 첨부파일 artsone 5316 2007.10.15 02:25
7 [Python] Python 1강 - 파이썬이란? artsOne 3419 2007.10.11 23:36
6 [Python] [스크랩] Python은 무엇인가? artsone 2001 2008.02.26 16:20