Python의 숫자형, 문자열 자료형에 대해 알아봅니다.
a = 123
print(type(a)) # <class 'int'>
b = 1.23
print(type(b)) # <class 'float'>
c = 4.24e10
print(c) # 42400000000.0
print(type(c)) # <class 'float'>
d = 0o10
print(d) # 8
print(type(d)) # <class 'int'>
e = 0x8ff # a = 10, b = 11 ...
print(e) # 2303
print(type(e)) # <class 'int'>
+, -, *, /: 사칙 연산.x ** y: x의 y제곱.%: 나눗셈 후 나머지를 반환.//: 나눗셈 후 몫을 반환. (정숫값)+=, -=, *=, /=, //=, %=, **=a += 1: a = a + 1a = "Life is too short, You need Python"
b = "a"
c = "123"
print(type(a)) # <class 'str'>
print(type(b)) # <class 'str'>
print(type(c)) # <class 'str'>
a = "Hello World" # 1
b = 'Python is fun' # 2
c = """Life is too short, You need python""" # 3
d = '''Life is too short, You need python''' # 4
food = "Python's favorite food is perl"
say = '"Python is very easy." he says.'
food = 'Python\'s favorite food is perl'
say = "\"Python is very easy.\" he says."
multiline = "Life is too short\nYou need python"
multiline='''Life is too short
You need python'''
multiline="""Life is too short
You need python"""
\n: 문자열 안에서 줄을 바꿀 때.\t: 문자열 사이에 탭 간격을 줄 때.\\: \를 그대로 표현할 때.\': 작은따옴표(')를 그대로 표현할 때.\": 큰따옴표(")를 그대로 표현할 때.head = "Python"
tail = " is fun!"
head + tail
print(head + tail) # Python is fun!
a = "python"
a * 2
print(a * 2) # pythonpython
a = "Life is too short"
len(a) # 17
a = "Life is too short, You need Python"
a[3] # 'e'
a[-1] # 'n': 뒤에서부터 세어 첫 번째가 되는 문자
[이상:미만:간격]a = "Life is too short, You need Python"
a[0:4] # 'Life'
a[19:] # 'You need Python'
a[:17] # 'Life is too short'
a[:] # 'Life is too short, You need Python'
a[::-1] # 'nohtyP deen uoY ,trohs oot si efiL'
a = "Pithon"
a[1] = 'y'
=> 오류. 문자열의 요솟값은 바꿀 수 있는 값이 아니다. (문자열은 '변경 불가능한(immutable) 자료형')
=> 슬라이싱 기법 사용.
a = "Pithon"
a[:1] + 'y' + a[2:]
a = "I eat %d apples." % 3
# 'I eat 3 apples.'
a = "I eat %s apples." % "five"
# 'I eat five apples.'
number = 3
a = "I eat %d apples." % number
# '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.'
| 코드 | 설명 |
|---|---|
| %s | 문자열(String) |
| %c | 문자 1개(character) |
| %d | 정수(Integer) |
| %f | 부동소수(floating-point) |
| %o | 8진수 |
| %x | 16진수 |
| %% | Literal % (문자 % 자체) |
a = "I have %s apples" % 3
# 'I have 3 apples'
b = "rate is %s" % 3.234
# 'rate is 3.234'
a = "Error is %d%." % 98
# 오류
b = "Error is %d%%." % 98
# 'Error is 98%.'
a = "%10s" % "hi"
# ' hi'
a = "%-10sjane." % 'hi'
# 'hi jane.'
a = "%0.4f" % 3.42134234
# '3.4213'
a = "I eat {0} apples".format(3)
# 'I eat 3 apples'
a = "I eat {0} apples".format("five")
# 'I eat five apples'
number = 3
a = "I eat {0} apples".format(number)
# 'I eat 3 apples'
number = 10
day = "three"
a = "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.'
a = "I ate {number} apples. so I was sick for {day} days.".format(number=10, day=3)
# 'I ate 10 apples. so I was sick for 3 days.'
a = "I ate {0} apples. so I was sick for {day} days.".format(10, day=3)
# 'I ate 10 apples. so I was sick for 3 days.'
a = "{0:<10}".format("hi")
# 'hi '
b = "{0:>10}".format("hi")
# ' hi'
c = "{0:^10}".format("hi")
# ' hi '
d = "{0:=^10}".format("hi")
# '====hi===='
e = "{0:!<10}".format("hi")
# 'hi!!!!!!!!'
:<10: 치환되는 문자열을 왼쪽으로 정렬하고 문자열의 총 자릿수를 10으로 맞춘다.:>: 오른쪽 정렬.:^: 가운데 정렬.y = 3.42134234
a = "{0:0.4f}".format(y)
# '3.4213'
b = "{0:10.4f}".format(y)
# ' 3.4213'
a = "{{ and }}".format()
# '{ and }'
name = '홍길동'
age = 30
dic = {'name':'홍길동', 'age':30}
a = f'나의 이름은 {name}입니다. 나이는 {age}입니다.'
# '나의 이름은 홍길동입니다. 나이는 30입니다.'
b = f'나는 내년이면 {age + 1}살이 된다.'
# '나는 내년이면 31살이 된다.'
c = f'나의 이름은 {dic["name"]}입니다. 나이는 {dic["age"]}입니다.'
# '나의 이름은 홍길동입니다. 나이는 30입니다.'
a = f'{"hi":<10}' # 왼쪽 정렬
# 'hi '
b = f'{"hi":>10}' # 오른쪽 정렬
# ' hi'
c = f'{"hi":^10}' # 가운데 정렬
# ' hi '
a = f'{"hi":=^10}' # 가운데 정렬하고 '=' 문자로 공백 채우기
# '====hi===='
b = f'{"hi":!<10}' # 왼쪽 정렬하고 '!' 문자로 공백 채우기
# 'hi!!!!!!!!'
y = 3.42134234
a = f'{y:0.4f}' # 소수점 4자리까지만 표현
# '3.4213'
b = f'{y:10.4f}' # 소수점 4자리까지 표현하고 총 자리수를 10으로 맞춤
# ' 3.4213'
a = f'{{ and }}'
# '{ and }'
a = f"난 {1500000:,}원이 필요해"
# '난 1,500,000원이 필요해'
a = "hobby"
a.count('b') # 2
a = "Python is the best choice"
a.find('b') # 14
a.find('k') # -1
a = "Life is too short"
a.index('t') # 8
a.index('k') # 오류
",".join('abcd') # 'a,b,c,d'
a = "hi"
a.upper() # 'HI'
a = "HI"
a.lower() # 'hi'
a= " hi "
a.rstrip() # ' hi'
a = " hi "
a.strip() # 'hi'
a = "Life is too short"
a.replace("Life", "Your leg") # 'Your leg is too short'
a = "Life is too short"
a.split() # ['Life', 'is', 'too', 'short']
b = "a:b:c:d"
b.split(':') # ['a', 'b', 'c', 'd']
s = "Python"
s.isalpha() # True
s = "Python3"
s.isalpha() # False
s = "Hello World"
s.isalpha() # False
s = "12345"
s.isdigit() # True
s = "1234a"
s.isdigit() # False
s = "12 34"
s.isdigit() # False
s = "Life is too short"
s.startswith("Life") # True
s.startswith("short") #False