파이썬 문법 복습하며 잊을만 하거나 잊었던 것들 기록하기
global 선언
def myfunc():
global x
x = "fantastic"
myfunc()
print("Python is " + x)
Python Data Types
Float can also be scientific numbers with an "e" to indicate the power of 10.
a = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
print(a)
결과 : Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.
for문 돌릴 때 range 주의하기
a = "banana"
for x in a:
print(x)
for x in range(len(a)):
print("d")
결과 :
b
a
n
a
n
a
d
d
d
d
d
d
Remove Whitespace
a = " Hello, World! "
print(a.strip())
결과 : "Hello, World!"
Replace String
print(a.replace("H", "J"))
Split String
print(a.split(","))
결과 : ['Hello', ' World!']
String Format
age = 36
txt = "My name is John, and I am {}"
print(txt.format(age))
중괄호 주의하자!
Escape Characters
Insert Items
thislist = ["apple", "banana", "cherry"]
thislist.insert(2, "watermelon")
print(thislist)
결과 : ['apple', 'banana', 'watermelon', 'cherry']
Extend List
thislist = ["apple", "banana", "cherry"]
tropical = ["mango", "pineapple", "papaya"]
thislist.extend(tropical)
print(thislist)
결과 : ["apple", "banana", "cherry","mango", "pineapple", "papaya"]
Remove Specified Index
thislist = ["apple", "banana", "cherry"]
thislist.pop(1)
print(thislist)
결과 : ["apple","cherry"]
그냥 pop()은 last in first out
del thislist[0]
thislist.clear()
→ 다 지우기
For문 돌릴 때 주의!!
thislist = ["apple", "banana", "cherry"]
for x in thislist:
print(x)
for i in range(len(thislist)):
print(thislist[i])
결과 :
apple
banana
cherry
apple
banana
cherry
Len 주의할 것!!
thislist = ["apple", "banana", "cherry"]
[print(x) for x in thislist]
→ 이런 방법도 있음
newlist = [x for x in range(10) if x < 5]
→ 이런 Syntax도 있음
Sort List
thislist.sort()
thislist.sort(reverse = True)
thislist.sort(key = str.lower)
thislist.reverse()
def myfunc(n):
return abs(n - 50)
thislist = [100, 50, 65, 82, 23]
thislist.sort(key = myfunc)
print(thislist)
Copy a List
thislist = ["apple", "banana", "cherry"]
mylist = thislist.copy()
print(mylist)
thislist = ["apple", "banana", "cherry"]
mylist = list(thislist)
print(mylist)
List Methods
참고 : W3schools