사용자 도구

사이트 도구


wiki:ai:python:문자열_연산_및_슬라이싱

문자열_연산_및_슬라이싱

  • description : 문자열 연산 및 슬라이싱
  • author : 도봉산핵주먹
  • email : hylee@repia.com
  • lastupdate : 2020-06-20

문자열_연산_및_슬라이싱

예제 코드

# Section04-2
# 파이썬 데이터 타입(자료형)
# 문자열, 문자열 연산, 슬라이싱
# 문자열 중요성(가장 많은 분야에서 사용)
 
# 문자열 생성
str1 = "I am Boy."
str2 = 'NiceMan'
str3 = """How are you?"""
str4 = '''Thank you!'''
 
# 문자열 출력
print(" == 변수타입 출력 ")
print(type(str1))
print(type(str2))
print(type(str3))
print(type(str4))
print()
 
# 문자열 길이
print(" == 문자열길이 출력 ")
print(len(str1))
print(len(str2))
print(len(str3))
print(len(str4))
print()
 
# 빈 문자열
str_t1 = ''
str_t2 = str()
 
print(" == 타입과 문자열길이 출력 ")
print(type(str_t1), len(str_t1))
print(type(str_t2), len(str_t2))
print()
 
# 이스케이프 문자 사용
 
escape_str1 = "Do you have a \"big collection\"?"
escape_str2 = 'What\'s on TV?'
escape_str3 = "What's on TV?"
escape_str4 = 'This is a "book".'
 
# 출력1
print(" == 문자열 출력 ")
print(escape_str1)
print(escape_str2)
print(escape_str3)
print(escape_str4)
print()
 
# 탭, 줄바꿈
t_s1 = "Tab \tClick!"
t_s2 = "New Line\n Start!!"
 
# 출력2
print(r" == '\t'가 입력된 변수 출력 ")
print(t_s1)
print(t_s2)
print()
 
# Raw String
raw_s1 = r'C:\Programs\python3\"'
raw_s2 = r"\\a\b\c\d"
raw_s3 = r'\'"'
raw_s4 = r"\"'"
 
# Raw String 출력
print(r" == 'r'가 입력된 변수 출력 ")
print(raw_s1)
print(raw_s2)
print(raw_s3)
print(raw_s4)
 
# 멀티라인 출력
print(" == 멀티라인 출력 ")
multi_str1 = \
    """
    문자열
    멀티라인
    테스트
    """
print(multi_str1)
 
multi_str2 = \
    '''
    문자열 멀티라인 
    역슬래시(\) \
    테스트
    '''
# 멀티라인(역슬래시) 출력
print(multi_str2)
 
print()
 
print(" == 문자열 연산")
# 문자열 연산
str_o1 = "Niceman"
str_o2 = "Orange"
str_o3 = "this is string example....wow!!! this is really string"
str_o4 = "Kim Lee Park Joo"
 
print(3 * str_o1)
print(str_o1 + str_o2)
print(dir(str_o1))
print('x' in str_o1) # x가 있는지 확인
print('i' in str_o1)
print('e' not in str_o2) # e가 없는지 확인
print('O' not in str_o2)
 
print()
# 문자열 형 변환
print(" == 문자열 형 변환")
print(str(77))  
print(str(10.4))
print(str(True))
print(str(complex(12)))
 
print()
# 문자열 함수
# 참고 : https://www.w3schools.com/python/python_ref_string.asp
print(" == 문자열 함수")
print("islower : ", str_o1.islower()) # 다 소문자인지 확인 Bloon
print("Capitalize: ", str_o1.capitalize()) # 맨 앞글자만 대문자로 바꿔서 출력
print("endswith?: ", str_o2.endswith("s"))  # 끝나는 문자가 's'인지 확인 Bloon
print("join str: ", str_o1.join(["I'm ", "!"])) # 문자 앞 뒤에 문자 붙이기
print("replace1: ", str_o1.replace('Nice', 'Good'))
print("replace2: ", str_o3.replace("is", "was", 3)) # 3은 바꿀 횟수
print("sorted: ", sorted(str_o1))  # 
print("reversed1: ", reversed(str_o2)) # list 형 변환을 해야 잘나오는걸 알기위해 Test
print("reversed2: ", list(reversed(str_o2))) # 문자를 리스트형태로 출력 (거꾸로)
 
print()
 
print(" == immutable ")
# immutable 설명
im_str = "Good Boy!"
 
print(dir(im_str))  # __iter__ 확인
# 출력
for i in im_str:
    print(i)
 
# im_str[0] = "T"  # 수정 불가(immutable)
print()
print(" == 슬라이싱 연습 ")
# 슬라이싱(인덱싱)
# 일부분 추출(정말 중요)
str_sl = 'Niceboy'
 
# 슬라이싱 연습 : 데이터분석 , 웹, 크롤링에 중요하다.
print(str_sl[0:3])
print(str_sl[:len(str_sl)])
print(str_sl[:len(str_sl) - 1])
print(str_sl[:])
# 마지막 2 는 출력 갯수를 지정한다.
print(str_sl[1:4:2])
print(str_sl[-3:6])
print(str_sl[1:-2])
print(str_sl[::-1])
print(str_sl[::2])
 
print()
 
# immutable 삭제
del str_sl
 
print(" == 아스키코드")
# 아스키코드
a = 't'
print(ord(a))
print(chr(116))

실행 콘솔

 == 변수타입 출력
<class 'str'>
<class 'str'>
<class 'str'>
<class 'str'>
 
 == 문자열길이 출력
9
7
12
10
 
 == 타입과 문자열길이 출력
<class 'str'> 0
<class 'str'> 0
 
 == 문자열 출력
Do you have a "big collection"?
What's on TV?
What's on TV?
This is a "book".
 
 == '\t'가 입력된 변수 출력
Tab     Click!
New Line
 Start!!
 
 == 'r'가 입력된 변수 출력
C:\Programs\python3\"
\\a\b\c\d
\'"
\"'
 == 멀티라인 출력
 
    문자열
    멀티라인
    테스트
 
 
    문자열 멀티라인
    역슬래시(\)     테스트
 
 
 == 문자열 연산
NicemanNicemanNiceman
NicemanOrange
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new
__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', '
isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', '
translate', 'upper', 'zfill']
False
True
False
False
 
 == 문자열 형 변환
77
10.4
True
(12+0j)
 
 == 문자열 함수
islower :  False
Capitalize:  Niceman
endswith?:  False
join str:  I'm Niceman!
replace1:  Goodman
replace2:  thwas was string example....wow!!! thwas is really string
sorted:  ['N', 'a', 'c', 'e', 'i', 'm', 'n']
reversed1:  <reversed object at 0x00000157400F88E0>
reversed2:  ['e', 'g', 'n', 'a', 'r', 'O']
 
 == immutable
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new
__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', '
isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', '
translate', 'upper', 'zfill']
G
o
o
d
 
B
o
y
!
 
 == 슬라이싱 연습
Nic
Niceboy
Nicebo
Niceboy
ie
bo
iceb
yobeciN
Ncby
 
 == 아스키코드
116
t

Tip

/var/services/web/dokuwiki/data/pages/wiki/ai/python/문자열_연산_및_슬라이싱.txt · 마지막으로 수정됨: 2023/01/13 18:44 (바깥 편집)