sorted.py
# 문자열 정렬하기 (sorted() 함수 )
# sorted() 함수 : 특정 변수에 저장된 값을 오름차순 정렬해주는 함수 ( 1,2,3... 사전순 정렬)
strdata = input('정렬한 문자열을 입력하세요 ? ')
ret1 = sorted(strdata) # 오름차순 정렬
ret2 = sorted(strdata, reverse=True) # 내림차순 정렬
print(ret1)
print(ret2)
ret1 = ''.join(ret1)
ret2 = ' '.join(ret2)
print('오름차순으로 정렬된 문자열은 < ' + ret1 + '> 입니다.')
print('내림차순으로 정렬된 문자열은 < ' + ret2 + '> 입니다.')
split.py
# 문자열을 특정문자로 분리하기 ( split() 함수 )
# split() 함수는 구분자(separator)로 구분되어 있는 문자열을 파싱(parsing)하는 역할을 한다.
url = 'http://www.naver.com/news/today=20160831'
log = 'name:홍길동 age:17 sex:남자 nation:조선'
ret1 = url.split('/') # url 변수에 저장된 데이터를 구분자('/')로 파싱함
print(ret1)
ret2 = log.split() # log 변수에 저장된 데이터를 공백으로 파싱함
print(ret2)
# ['name:홍길동', 'age:17', 'sex:남자', 'nation:조선']
for data in ret2:
d1, d2 = data.split(':') # data 변수에 저장된 데이터를 구분자(':')로 파싱함
print('%s -> %s' %(d1, d2))
str.py
# 수치형 자료를 문자열로 변환하기 ( str() 함수 )
num1 = 1234
num2 = 3.14
numstr1 = str(num1) # 정수를 문자열로 변환
numstr2 = str(num2) # 실수를 문자열로 변환
print(type(numstr1))
print(type(numstr2))
print('num1을 문자열로 변환한 값은 "%s" 입니다.' %numstr1)
print('num2을 문자열로 변환한 값은 "%s" 입니다.' %numstr2)
print('num1을 문자열로 변환한 값은 "%d" 입니다.' %num1)
strip.py
# 문자열 좌.우 좌우공백 제거하기 ( lstrip(), rstrip(), strip() 함수 )
# lstrip() : 문자열 좌측의 공백을 없애주는 함수
# rstrip() : 문자열 우측의 공백을 없애주는 함수
# strip() : 문자열 좌.우의 공백을 없애주는 함수
txt = ' 양쪽에 공백이 있는 문자열입니다. '
ret1 = txt.lstrip()
ret2 = txt.rstrip()
ret3 = txt.strip()
print('<'+txt+'>')
print('<'+ret1+'>') # 왼쪽 공백 제거
print('<'+ret2+'>') # 오른쪽 공백 제거
print('<'+ret3+'>') # 양쪽 공백 제거
list01.py
# 0 1 2 3
L = [1,2,3,4]
print (type(L))
print ("len(L)->" , len(L))
print (" L[1]->" , L[1])
print (" L[-1]->" , L[-1]) # 맨뒤
print (" L[1:3]->" , L[1:3]) # 1, 2 까지
print ("L + L ->" , L + L)
print ("L * 3 ->" , L * 3)
list02.py
# List안 List가능
kk=[1,2,3,['a','b','c']]
print("kk->",kk)
print("kk[-1][1]->",kk[-1][1])
list03.py
# range : List나 Tuple를 사용, 저장하지 않더라도 특정범위의
# 숫자 시퀀스 생성
L = range(10) # 0,1,2,3,4,5,6,7,8,9
print(L)
print("L[::2]->", L[::2]) # start : end : jump
A = L[::2]
for aa in A:
print('A->', aa)
tuple01.py
# Tuple은 List의 Read Only
t = (1,2,3,4,5)
print("len(t)->",len(t))
print("t[0]->", t[0])
print(t[-1])
print(" t[0:2] ->", t[0:2])
print("t[::2]->",t[::2])
tuple02.py
# tuple은 정의할때 괄호 붙이지 않아도 됨
colors = 'red', 'green', 'blue', 'yellow', 'orange'
print('colors->', colors)
print('colors len -> ', len(colors))
# unpacking
a,b,c,d,e = colors
print('a->', a)
print('c->', c)
# 마지막 item 가져오기
the_last = colors[-1]
print('the_last -> ', the_last)
dictionary01.py
d = {'one': 'hana', 'two': 'dul', 'three': 'set'}
d['four'] = 'net' # 새 항목의 삽입
print("d1 -> ", d)
d['one'] = 1 # 기존 항목의 값 변경
print("d2 -> ", d)
print('one' in d) # 키에 대한 멤버쉽 테스트
dictionary02.py
d3 = {'one': 1, 'two': '둘', 'three': '삼', 'four': '사'}
print("d3.keyS()->", d3.keys()) # 키만 리스트로 추출함, 임의의 순서
print("Type(d3.keys())->", type(d3.keys())) # 키만 리스트로 추출함, 임의의 순서
print("d3.values()->", type(d3.values())) # 값만 리스트로 추출함, 임의의 순서
print("d3.values()->", d3.values()) # 값만 리스트로 추출함, 임의의 순서
print("d3.items()->", d3.items()) # 키와 값의 튜플을 리스트로 반환함
seq01.py
# 시퀀스 자료형의 지원 연산 슬라이싱
print ("---------------------------")
# 0123456
s = 'abcdef'
print("s[1:3]", s[1:3])
print("s[1:]", s[1:])
print("s[:]", s[:])
print("s[-100:100]", s[-100:100]) # -100 -> 처음 값, 100 -> 마지막 값
print("s[-30:100]", s[-30:100]) # -30 -> 처음 값, 100 -> 마지막 값
print("[-2:100]", s[-2:100]) # -2 -> 처음 값, 100 -> 마지막 값
print("s[-1:100]", s[-1:100]) # -1 -> 처음 값, 100 -> 마지막 값
# 시퀀스 자료형의 지원 연산 확장 슬라이싱
# L[start:end:step]: 인덱싱되어지는 각 원소들 사이의 거리가 인덱스 기준으로 step 만큼 떨어짐
print ("---------------------------")
print("s[::2]", s[::2]) # step:2 - 각 원소들 사이의 거리가 인덱스 기준으로 2가 됨
print("s[::-1]", s[::-1]) # step:-1 - 왼쪽 방향으로 1칸씩
seq02.py
# 시퀀스 자료형의 지원 연산 -> 멤버십 테스트
print ("---------------------------")
s = 'abcde'
print("'c' in s ", 'c' in s)
t = (1,2,3,4,5)
print("2 in t", 2 in t)
print("10 in t", 10 in t)
print("10 not in t", 10 not in t)
seq03.py
print ("-----문자열 정의 및 기초 연산 -> 문자열 연산------")
print ("-----문자열 변경을 위해서는 여러 Slicing 연결 활용 ------")
print ("-----[주의] 문자열 자체가 변경되는 것이 아니라 새로운 문자열을 생성하여 재 할당하는 것임 ------")
print ("-----[주의] 연결되어 새로운 문자열이 된 것이지 수정된 것이 아님 ------")
print ()
s = 'spam and egg'
s = s[:4] + ', cheese, ' + s[5:]
print("s[:4] + ', cheese, ' + s[5:] ", s)
strMethod01.py
print ("---------------------------")
print ("------ 문자열 메소드 ------")
s = 'i like programming.'
print("s.upper()", s.upper())
print("s.upper().lower()", s.upper().lower())
print("'I Like Programming'.swapcase()", 'I Like Programming'.swapcase())
print("s.capitalize()", s.capitalize())
print("s.title()", s.title())
'PYTHON' 카테고리의 다른 글
20221201 def (0) | 2022.12.01 |
---|---|
20221128, 1129 List, String, Tuple, File (0) | 2022.11.28 |
20221124 제어문, 함수(1) (0) | 2022.11.25 |
20221123 string, variable, arithmetic, inOperator, compOperator, if (0) | 2022.11.23 |
20221121 first, input, hex, import (0) | 2022.11.22 |
댓글