# Hello world 문장을 변수 sa에 대입 후 출력해 봅니다.
>>> sa = 'Hello world' or "Hello world"
>>> print(sa)
Hello world
>>> type(sa)
str
# Tom's favorite food 문장을 변수 sb에 대입 후 출력해 봅니다.
#문법상 충돌 발생 위험이 있는 따옴표는 고려해 사용.
>>> sb = "Tom's favoritefood is pizza"
>>> print(sb)
Tom's favoritefood is pizza
# '"You are right." I said.' 문장을 변수 sc에 대입 후 출력해 봅니다.
>>> sc = '"You are right." I said.'
>>> print(sc)
"You are right." I said.
# Tom's favorite
# food 문장을 줄바꿈을 포함하여 변수 sd에 대입 후 출력해 봅니다. (줄 바꿈 방법: 문장 앞 뒤로 큰 따옴표 """ 사용)
>>> sd = """ Tom's favorite
food"""
>>> print(sd)
Tom's favorite
food
# "You are right"
# I said. 문장을 줄바꿈을 포함하여 변수 se에 대입 후 출력해 봅니다. (줄 바꿈 방법: 문장 앞 뒤로 작은 따옴표 ''' 사용)
>>> se = '''"You are right."
I said.'''
>>> print(se)
"You are right."
I said.
# 12\n34 문장을 변수에 대입하여 출력해 봅니다.
# 백슬래시: \ (백 슬래시는 파이썬에서 enter의 기능과도 같음. )
>>> s = '12\n34'
>>> print(s)
12
34
# this/has/no/special/characters 문장을 sg 변수에 대입하여 출력해 봅니다.
>>> sg = 'this\has\\no\special\characters'
>>> print(sg)
#숫자형 30
>>> a = 30
>>> print(a)
>>> print(type(a))
30
<class 'int'>
#문자형 '30'
>>> b = '30'
>>> print(b)
>>> print(type(b))
30
<class 'str'>
# this is the first half 문장과 and this is the second half 문장을 +를 사용하여 연결합니다.
>>> print('this is the first half' + ' and this is the second half')
this is the first half and this is the second half
#eng는 숫자형이 됨. 따라서 error
>>> from logging import error
>>> eng = 80
>>> result = '영어 점수 : ' + eng + '점'
#다른 데이터 타입을 같은 데이터 타입으로 변환시킴. str()
>>> eng = 80
>>> result = '영어 점수 : ' + str(eng) + '점'
>>> print(result)
영어 점수 : 80점
# 언더스코어(_)를 50번 연결하여 출력해봅니다.
>>> print('_' * 50)
# this is the first half and this is the second half 문장의 공백을 포함한 글자수를 세어봅니다.
# len() -> 'lenth 길이'라는 의미를 가지는 함수를 사용
>>> len('this is the first half and this is the second half')
50
문자열 포맷: %S
- 문자열 데이터형을 포맷
# name 변수, 문자열 포맷 기능을 활용하여 '나는 김수영입니다'라는 출력 결과가 나오게 print 하세요. >> name = '김수영' >> print('나는 %s입니다' %name) 나는 김수영입니다
문자열 포맷: %D
- 정수형 숫자를 포맷
# age 변수, 문자열 포맷 기능을 활용하여 '나이는 20살입니다'라는 출력 결과가 나오게 print 하세요. >> age = 20 >> print('나이는 %d살입니다'%age) 나이는 20살입니다
문자열 포맷: %2D
>> year = 2022 >> month = 9 >> day = 5 # 위 변수, 문자열 포맷 기능을 활용 2022-09-05라는 출력 결과가 나오게 print하세요. >> a = '%d-%02d-%02d' % (year, month, day) >> print(a) 2022-09-05
문자열 포맷: %2.F
#height 변수, 문자열 포맷 기능을 활용해 '키는 172.50입니다' 라는 출력 결과가 나오게 print 하세요. >> height = 172.5 >> print('키는 %.2f입니다'%height) #값의 소수점 둘째 자리까지 출력 키는 172.50입니다
문자열(STR) FORMAT
- FORMAT 함수는 %와 기능이 같음.
- FORMAT 함수에서 들어가야 할 위치는 {} 중괄호로 지정함.
#I have children 문장에서 문자열 포맷 기능 활용 children 앞에 3을 추가합니다. >>>'I have {} children'.format(3) #%함수 >>> "I have %d children." %3 'I have 3 children'
# children 앞에 three를 추가합니다. >> 'I have {} children'.format('three') #%함수 >> "I have %s children." %"three" I have three children
# children 앞에 변수 e를 추가합니다. (e = 3) >> e = 3 >> 'I have {} children'.format(e) I have 3 children
#c children 앞과 뒤에 각각 실수 3.14와 문자 wow를 추가합니다. >>'I have {} children {}'.format(3.14, 'wow') >> 'I have {1} children {0}'.format('wow', 3.14) I have 3.14 children wow
문자열 포맷 기능을 활용해 변경하기
# This is True! -> This is 100% True >>'This is %s True!' %'100%' This is 100% True!
# "" -> " Good" (전체 10자리, 우측 정렬) >> "%10s" %"Good" ' Good'
# "" -> " Good" (전체 10자리, 좌측 정렬) >> "%-10s" %"Good" 'Good '
>> pi = 3.141592 # "" --> "3.14" (pi 변수 활용) >> "%.2f" %pi 3.14
# 위의 조건에서 전체 자리 수를 20자리로 맞춥니다. >> "%20.2f" %pi ' 3.14'
FORMAT( )을 이용한 문자열 포맷
>> name = '최시연' >> age = 33 >> eyesight = 1.5 #위 변수와 format 메써드 사용 아래와 같이 결과가 나오게 출력하세요. #이름: 최시연, 나이: 33세, 시력: 1.5 >> a = '이름:{}'.format(name) >> b = '나이:{}세'.format(age) >> c = '시력:{}'.format(eyesight) >> print(a,',',b,',',c) >> print('이름:{}, 나이:{}세, 시력:{}'.format(name, age, eyesight)) 이름:최시연 , 나이:33세 , 시력:1.5 이름:최시연, 나이:33세, 시력:1.5
>> a = 4.5560 >> b = 'Argentine Pesos' >> c = 1 # 위 변수와 format 함수 활용 # are worth US$ -> 4.56 Argentine Pesos are worth US$1 >> '{0:.2f} {1}are worth US${2}'.format(a, b, c) 4.56 Argentine Pesosare worth US$1
#{우리집}에 놀러와요 -> {우리집}에 자주 놀러와요 >>'{{우리집}}에 {} 놀러와요'.format('자주') {우리집}에 자주 놀러와요
FORMAT 메써드 대신 앞에 F 사용
>> a = 3 >> b = 'wow' # I have children --> I have 3 children wow # format 메써드와 %를 사용하지 않고 a와 b를 활용하여 변경 >> f"I heve {a} children {b}" I heve 3 children wow
# 상기 조건에서 변수 a에 2를 더하면서 입력 >> f"I have {a+2} children {b}" I have 5 children wow
# {good} --> {good}{day} # 문자열 f 포맷 기능을 이용하여 변경 >> f'{{good}}''{day}' {good}{day}
>>> sa = "Korean culture"
# 내장함수 사용 문자 u의 개수를 확인합니다.
>>> sa.count('u')
2
# 내장함수 사용 문자 k의 인덱스 번호를 확인합니다.
>>> sa.find('K')
0
>>> sa.find('k')
-1
>>> sa.index('K')
0
# join 함수 사용 Korean culture --> K o r e a n c u l t u r e 로 변경합니다.
>>> " ".join('Korean culture')
K o r e a n c u l t u r e
# join 함수 사용 문자열 123456789 a 1, 2, 3, 4, 5, 6, 7, 8, 9 로 변경합니다.
>>> ", ".join('123456789')
1, 2, 3, 4, 5, 6, 7, 8, 9
# 내장함수를 사용하여 문장을 전부 대문자로 변경합니다.
>>> sa.upper()
KOREAN CULTURE
# 내장함수를 사용하여 문장을 모두 소문자로 변경합니다.
>>> sa.lower()
korean culture
# 내장 함수를 사용하여 ' Korean ' 문장을 'Korean'으로 변경합니다.
>>> sb = ' Korean culture '
>>> sb.strip()
' Korean culture '
# 내장함수를 사용하여 ' Korean ' 문장에서 왼쪽 공백만 제거합니다.
>>> sb.lstrip()
'Korean culture '
# 내장함수를 사용하여 ' Korean ' 문장에서 오른쪽 공백만 제거합니다.
>>> sb.rstrip()
' Korean culture'
# 내장함수를 사용하여 Korean culture를 American culture로 변경합니다.
>>> sa.replace("Korean", "American")
'American culture'
# 내장함수를 사용하여 Korean culture를 ['Korean', 'culture']로 분리합니다.
>>> sa.split()
['Korean', 'culture']
# 내장함수를 사용하여 Korean & culture를 ['Korean', 'American']로 분리합니다.
>>> sc = "Korean & American"
>>> sc.split("&")
['Korean ', ' American']
# 화면에 c:\nano를 출력합니다.
# 역슬래쉬(\)는 enter 기능.
>>> print('C:\nano')
>>> print(r'C:\ nano')
C:
ano
C:\ nano
# 나의 주민번호는 990306-2030998 입니다.
# 연월일과 그 뒤 숫자 부분을 나누어 출력합니다.
>>> me = '990306-2030998'
>>> birth = me[:6]
>>> print(birth)
990306
>>> uni_code = me[-7:]
>>> print(uni_code)
2030998
>>> me.split('-')
['990306', '2030998']
# 나의 주민번호에서 성별 표시 숫자 출력
>>> me[-7]
'2'
# a:b:c:d --> a@b@c@d 로 변경합니다.
>>> 'a:b:c:d'.replace(':', "@")
a@b@c@d
# a&b&c&d --> ['a', 'b', 'c', 'd'] 로 변경합니다.
>>> 'a&b&c&d'.split('&')
['a', 'b', 'c', 'd']
# 문자열 '720'을 정수형으로 변환
>>> type(int('720'))
# '720' --> 720 (int)
int
# 정수 100을 문자열 '100'으로 변환
>>> type(str(100))
# 100 --> '100' (str)
str
# 아래의 문자열에서 '홀'만 출력
>>> game = '짝홀짝홀짝홀'
>>> print(game[1:])
>>> print(game[1::2])
>>> print(game[::2])
홀짝홀짝홀
홀홀홀
짝짝짝
# 전화번호에서 ('-')을 제거하고 출력
>>> pn = "010-1234-5678"
>>> pn.replace('-', '')
01012345678
# 삼성전자 웹 주소에서 도메인(com)만 출력
# https://www.samsung.com
>>> url = 'https://www.samsung.com'
>>> url[-3:]
'com'
https://colab.research.google.com/drive/1_Kq2gpp-R0XC2JivmLY_yFvLI1Up8kPT?usp=sharing