1. 문자열 연결하기
head = 'python'
tail = ' is fun!'
body = head + tail
display(body)
python is fun!
2. 문자열 곱하기
a='python'
b = a*2
display(b)
pythonpython
print('=' * 50)
print('My program')
print('=' * 50)
==================================================
My program
==================================================
3. 문자열 길이구하기
a = 'Life is too short'
display(len(a))
17
4. 문자열 인덱싱
a = "Life is too short, You need Python"
display(a[3])
display(a[-3])
e
h
5. 문자열 슬라이싱
a = "Life is too short, You need Python"
display(a[:4])
display(a[:])
Life
Life is too short, You need Python
6. 슬라이싱으로 문자열 나누기
a = "20010331Rainy"
year = a[:4]
day = a[4:8]
weather = a[8:]
display(year)
display(day)
display(weather)
2001
0331
Rainy
7. 문자열 포맷팅
a = 'I eat %s apples.' % 'five'
display(a)
a = 'I eat %d apples.' % 5
display(a)
a = 'I eat %d apples and %d grapes' % (5,3)
display(a)
I eat five apples.
I eat 5 apples.
I eat 5 apples and 3 grapes
8. 포맷팅된 문자열 삽입
a = 'abc{0:<5}defg'.format('123') # 5자리로 맞춰서 왼쪽정렬된 문자열 삽입
display(a)
a = 'abc{0:>5}defg'.format('123') # 5자리로 맞춰서 오른쪽정렬된 문자열 삽입
display(a)
a= 'abc{0:=<5}defg'.format('123') # 5자리로 맞춰서 오른쪽정렬된 문자열 삽입, 공백은 '='로 채움
display(a)
abc123 defg
abc 123defg
abc123==defg
9. 소수점 표현하기
y = 3.42134234
x = '{0:0.4f}'.format(y)
display(x)
3.4213
10. 문자개수 세기
a = 'happy'
a.count('p')
display(a)
2
11. 특정 문자 위치 알려주기1(첫번째)
a = "Python is the best choice"
display(a.find('b'))
display(a.find('k'))
14
-1
12. 특정 문자 위치 알려주기2(첫번째)
a = "Python is the best choice"
display(a.index('b'))
#display(a.index('k')) #일치하는 문자가 없으면 에러발생
14
13. 문자열 삽입
a = ",".join('abcd')
display(a)
a,b,c,d
14. 소문자를 대문자로 바꾸기
a = 'Hi'
b = a.upper()
display(b)
HI
15. 대문자를 소문자로 바꾸기
a = 'Hi'
b = a.lower()
display(b)
hi
16. 왼쪽 공백 지우기
a = ' h i '
b = a.lstrip()
display(b)
h i
17. 오른쪽 공백 지우기
a = ' h i '
b = a.rstrip()
display(b)
h i
18. 양쪽 공백 지우기
a = ' h i '
b = a.strip()
display(b)
h i
19. 문자열 바꾸기
a = "Life is too short"
b = a.replace("Life", "Your leg")
display(b)
Your leg is too short
20. 문자열 나누기
a = "Life is too short"
b = a.split()
display(b)
c = "a:b:c:d"
d = b.split(':')
display(d)
['Life', 'is', 'too', 'short']
['a', 'b', 'c', 'd']
21. raw String 표현
raw string은 backslash(\)를 문자로 인식시키기 위해 사용
str = r'\test string' # 문자열 앞에 r을 붙임으로서 \를 그대로 인식
str1 = '\test string' # '\t'를 탭으로 인식함
print(str)
print(str1)
\test string
est string
'Language > python' 카테고리의 다른 글
[ Python 자료형 ] 집합(Set) 관리 (0) | 2019.12.08 |
---|---|
[ Python 자료형 ] Dictionary (0) | 2019.12.08 |
[ Python 자료형 ] Tuple (0) | 2019.12.08 |
[ Python 자료형 ] LIST 관리 (0) | 2019.12.06 |
django_Virtualenv를 통해 가상한경을 만든뒤, Django 프로젝트 생성하기 (0) | 2019.12.06 |