본문 바로가기

Basic Grammar/Python

DataType1 - String

1. 문자열 연산하기



>>> head = "Python"

>>> tail = " is fun!"

>>> head + tail

'Python is fun!'





>>> a = "python"

>>> a * 2

'pythonpython'





print("=" * 50)

print("My Program")

print("=" * 50)



==================================================

My Program

==================================================



------------------------------------------------------



2. 문자열 인덱싱과 슬라이싱



>>> a = "Life is too short, You need Python"

>>> a[3]

'e'

>>> a[0:4]

'Life'



문자열 요소값은 바꿀 수 없다. ( a[1]='y'  불가)



------------------------------------------------------



3. 문자열 포매팅



>>> "I eat %d apples." % 3

'I eat 3 apples.'


number=10

day="three"
>>> "I ate %d apples. so I was sick for %s days." % (number, day)

'I ate 10 apples. so I was sick for three days.'



>>> "I eat {0} apples".format(3)

'I eat 3 apples'

>>> "I eat {0} apples".format("five")

'I eat five apples'

>>> "I ate {0} apples. so I was sick for {1} days.".format(number, day)

'I ate 10 apples. so I was sick for three days.'



>>> name = '홍길동'

>>> age = 30

>>> f'나의 이름은 {name}입니다. 나이는 {age}입니다.'

'나의 이름은 홍길동입니다. 나이는 30입니다.'





------------------------------------------------------



4. 문자열 관련 함수들



문자 개수 세기(count)
>>> a = "hobby"
>>> a.count('b')
2




위치 알려주기1(find)
>>> a = "Python is the best choice"
>>> a.find('b')
14
>>> a.find('k')
-1


문자열 삽입(join)
>>> ",".join('abcd')
'a,b,c,d'


소문자를 대문자로 바꾸기(upper)
>>> a = "hi"
>>> a.upper()
'HI'


대문자를 소문자로 바꾸기(lower)
>>> a = "HI"
>>> a.lower()
'hi'


왼쪽 공백 지우기(lstrip)
>>> a = " hi "
>>> a.lstrip()
'hi '


오른쪽 공백 지우기(rstrip)
>>> a= " hi "
>>> a.rstrip()
' hi'


양쪽 공백 지우기(strip)
>>> a = " hi "
>>> a.strip()
'hi'


문자열 바꾸기(replace)
>>> a = "Life is too short"
>>> a.replace("Life", "Your leg")
'Your leg is too short'


문자열 나누기(split)
>>> a = "Life is too short"
>>> a.split()
['Life', 'is', 'too', 'short']
>>> b = "a:b:c:d"
>>> b.split(':')
['a', 'b', 'c', 'd']







'Basic Grammar > Python' 카테고리의 다른 글

Iterable vs. Not Iterable  (0) 2022.06.27
DataType5 - Set  (0) 2022.06.26
DataType4 - Dictionary  (0) 2022.06.26
DataType3 - Tuple  (0) 2022.06.26
DataType2 - List  (0) 2022.06.26
Recent Posts
Popular Posts
Recent Comments