상세 컨텐츠

본문 제목

스트링에 대한 기초 지식

Python

by techbard 2015. 7. 7. 15:46

본문

반응형
  • 특성
    1. 문자열을 담는 컨테이너이다.
    2. 자체적인 메쏘드를 가지고 있다.
  • 예제
    • 컨테이너

# 문자열 객체를 생성

emptyString = ''

print(len(emptyString))
결과)0
# 문자열 객체 결합string1 = 'pine'string2 = 'apple'strings = string1 + string2print(strings)
결과)pineapple
# 문자열 객체는 str 객체이다.fruitName = 'apple'print(type(fruitName))
결과)<class 'str'>
  • 문자열 슬라이싱

# 시작 위치부터 두 개 요소를 추출

fruitName = 'apple'print(fruitName[:2])
결과)ap
# 시작 요소 부터 2개씩 추출fruitName = 'watermelon'print(fruitName[::2])
결과)wtreo
# 시작 요소 부터 마지막 요소 에서 5개를 제외한 요소까지 추출fruitName = 'watermelon'print(fruitName[:-5:])
결과)water
# 슬라이스 파라미터의 의미 (1st: 시작, 2nd: 끝, 3rd: 건너뛰기)s = 'banana'print(s[1:6:2])
결과)aaa
# 2nd 파라미터는 끝 위치를 지정하므로 건너뛰기도 끝 위치 내에서만 작동한다.s = 'banana'print(s[1:5:2])
결과)aa

 

# 2nd 파라미터가 무효한 값이면 유효한 값으로 작동한다.

s = 'banana'

 

print(s[1:100])
결과)anana
# 문자열 뒤집기s = 'hello'

 

print(s[::-1])
결과)olleh
  • 문자열 멤버쉽 체크

# 문자열이 대상의 요소인지 아닌지 리턴한다.

l = ['a', 'b', 'c']

print(str('a' in l))

 

결과)

True

 

# 중첩 리스트까지 체크하지는 않는다.

sl = ['d', 'e', 'f']
l = ['a', 'b', 'c', sl]

print(str('f' in l))

 

결과)

False

 

# 멤버쉽 체크 대상을 명확하게 지정하면 요소 체크가 가능하다.

sl = ['d', 'e', 'f']
l = ['a', 'b', 'c', sl]
print(str('f' in l[3]))

 

결과)

True

  • 스트링에 대한 인덱스 할당

# 스트링에 대한 인덱스 읽어오기

s = 'hello'

print (s[-1:])

 

결과)

o

 

# 스트링에 대한 인덱스 할당은 가능하지 않다.

s = 'hello'
s[-1:] = 'y'

 

결과)

TypeError: 'str' object does not support item assignment

 

# 할당 대신에 읽어내어 원하는 형태를 더해준다.

s = 'hello'
print(s[:-1] + 'y')

 

결과)

helly

  • 자주 사용되는 스트링 조작

# split() 메쏘드

s = 'pine_apple'parts = s.split('_')print(parts)
결과)['pine', 'apple'] # split() 메쏘드는 리스트를 리턴한다.
# '/' 구분자의 사용s = 'super/man'parts = s.split('/')print(parts)
결과)['super', 'man']
# join() 메쏘드s = 'super/man'parts = s.split('/')original_s = '/'.join(parts)print(original_s)
결과)super/man
# 매우 자주 사용되는 리스트를 스트링으로 변환하는 트릭l = ['I am', ' a list']s = ''.join(l)print(s)print(type(s))

 

결과)I am a list<class 'str'>
  • 화이트스페이스 문자 잘라내기

# strip() 메쏘드의 사용 #1

s = '           superman                 'sStriped = s.strip()print(sStriped)
결과)superman

# strip() 메쏘드의 사용 #2

s = '####  superman'sStriped = s.strip('# ')print(sStriped)
결과)superman
  • 출력 포맷팅

# 문자열 포맷팅을 신경쓰지 않고 보이는 그대로 출력

s = '''\this is astring line andmany others'''

 

print(s)
결과)this is astring line and

 

many others
# 출력간에 개행이 아닌 원하는 세퍼레이터 넣기for i in range(1, 11):

 

    print(i, end=' ')
결과)1 2 3 4 5 6 7 8 9 10 
### List를 String으로 바꾸는 방법

def main():
    # 방법 1
    ls = ['we', 'are', 'hero']
    print(ls, end=' ') ; print('->', end=' ') ; print(' '.join(ls))

    print('\t')

    # 방법 2
    ln = [1, 2, 3]
    print(ln, end=' ') ; print('->', end=' ') ; print(' '.join(map(str, ln)))

    print('\t')

    # 방법 3
    ln = [1, 'test', 3]
    print(ln, end=' ') ; print('->', end=' ') ; print(' '.join(map(str, ln)))

    print('\t')

    # 방법 4
    lw = ['Wow', 'very', 'nice', 100]
    strs = ''
    for el in lw:
        strs += str(el) + ' '
    print(lw, end=' ') ; print('->', end=' ') ; print(strs.rstrip())

    pass

if __name__ == '__main__':
    main()

# 결과
['we', 'are', 'hero'] -> we are hero
	
[1, 2, 3] -> 1 2 3
	
[1, 'test', 3] -> 1 test 3
	
['Wow', 'very', 'nice', 100] -> Wow very nice 100
반응형

관련글 더보기

댓글 영역