문자열

  • 시퀀스자료형으로 문자형 data를 메모리에 저장
  • 영문자 한글자는 1byte의 메모리공간을 사용
import sys # sys 모듈을 호출
print (sys.getsizeof("a"), sys.getsizeof("ab"), sys.getsizeof("abc"))
50 51 52
  • 문자열의각문자는개별주소(offset)를가짐
  • 이주소를사용해할당된값을가져오는것이인덱싱
a = "abcde"
print (a[0], a[4]) 
print (a[-1], a[-5]) 
a e
e a

Str Function

문자열 함수 1

1) len() : 문자열의 문자개수를 반환
2) upper() : 대문자로 변환
3) lower() : 소문자로 변환
4) capitalize() : 첫문자를 대문자로 변환
5) title() : 제목형태로 변환, 띄어쓰기 후 첫 글자만 대문자
6) count('bc') : 문자열 a에 'bc'가 들어간 횟수 반환
7) find('bc') : 문자열 a에 'bc'가 들어간 위치(오프셋) 반환
8) rfind('bc') : 문자열 a에 'bc'가 들어간 위치(오프셋) 반환
9) startswith('bc') : 문자열 a는 'bc'로 시작하는 문자열여부 반환
10) endswith('bc') : 문자열 a는 'bc'로 끝나는 문자열여부 반환
mystr = "BoOst Camp X UP stage"
len(mystr)
21
mystr.upper()
'BOOST CAMP X UP STAGE'
mystr.lower()
'boost camp x up stage'
mystr.capitalize()
'Boost camp x up stage'
mystr.title()
'Boost Camp X Up Stage'
print(mystr.count('bc'))
print(mystr.count('st'))
0
2
mystr.find('st')
3
mystr.rfind('st')
16
mystr.startswith('BoOst')
True
mystr.endswith('stage')
True

문자열 함수2

11) strip() 좌우 공백 제거
12) rstrip() 오른쪽 공백 제거
13) lstrip() 왼쪽 공백 제거
14) split() 공백을 기준으로 나눠 리스트로
15) split('abc') abc를 기준으로 나눠 리스트로
16) isdigit() 문자열이 숫자인지 여부
17) islower() 문자열이 소문자인지 여부
18) isupper()
A = '   Hello    '
A.strip()
'Hello'
A.rstrip()
'   Hello'
A.lstrip()
'Hello    '
B = 'Q W E R T Y'
B.split()
['Q', 'W', 'E', 'R', 'T', 'Y']
B.split('W')
['Q ', ' E R T Y']
'12345'.isdigit()
True
12345.isdigit()
  File "<ipython-input-40-11e7faa77f03>", line 1
    12345.isdigit()
          ^
SyntaxError: invalid syntax
'QWERY'.isupper()
True
'QWERy'.isupper()
False
'QWERy'.islower()
False
'qwer'.islower()
True

Scoping Rule

  • 지역변수(local variable) : 함수내에서만 사용
  • 전역변수(Global variable) : 프로그램전체에서 사용

    Swap

    변수 간의 값을 교환(SWAP)할 수 있는 함수
def swap_value (x, y):
    temp = x
    x = y
    y = temp
def swap_offset (offset_x, offset_y):
    temp = input_list[offset_x]
    input_list[offset_x] = input_list[offset_y]
    input_list[offset_y] = temp
def swap_reference (input_list, offset_x, offset_y):
    temp = input_list[offset_x]
    input_list[offset_x] = input_list[offset_y]
    input_list[offset_y] = temp
input_list = [5,6,7,8,9]
swap_value(input_list[0],input_list[1])
input_list
[5, 6, 7, 8, 9]
swap_offset(0,1) # input_list라는 전역변수값을 직접 수정했음.
input_list
[6, 5, 7, 8, 9]
swap_reference(input_list, 3,4) # input_list 객체의 주소 값을 받아 값을 변경
input_list
[6, 5, 7, 9, 8]

이외에 알아둬야할 것들

function type hints

  • Type hints의 장점

    (1) 사용자에게 인터페이스를 명확히 알려줄 수 있다.

    (2) 함수의 문서화시 parameter에 대한 정보를 명확히 알 수 있다.

    (3) mypy 또는 IDE, linter 등을 통해 코드의 발생 가능한 오류를 사전에 확인

    (4) 시스템 전체적인 안정성을 확보할 수 있다.

def type_hint_example(name: str) -> str:
    return f"Hello, {name}"
type_hint_example('Moon')
'Hello, Moon'
def insert(self, index: int, module: Module) -> None:
    r"""Insert a given module before a given index in the list.
    Args:
        index (int): index to insert.
        module (nn.Module): module to insert
    """
    for i in range(len(self._modules), index, -1):
        self._modules[str(i)] = self._modules[str(i - 1)]
    self._modules[str(index)] = module

+ Recent posts