코드스테이츠(컴퓨터 공학 기본)(Computer Science) Session 5 / Sprint 1(다양한 메소드의 활용)

나이브한코딩·2021년 7월 10일
0
post-thumbnail

다양한 메소드의 활용

1. rjust(width, [fillchar]) :

  • 원하는 문자를 따로 지정하고, 다른 문자열로 앞 부분을 채워줄 수 있다.
#"002"
print("2".rjust(3,"0"))
 
#"50000"
print("50000".rjust(5,"0"))
 
#"00123"
print("123".rjust(5,"0"))
 
#"aa123"
print("123".rjust(5,"a"))

2. zfill(width):

#"002"
print("2".zfill(3))
 
#"50000"
print("50000".zfill(5))
 
#"00123"
print("123".zfill(5))

3. Split :

string_ = "Hello, I am Jack and I am a data scientist"
print(string_) # Hello, I am Jack and I am a data scientist
print(string_[1]) # e

string_list = string_.split(" ")
string_list

string_.startswith('Hello')

string_.endswith('scientist')

string_.endswith('tist')

print(string_.replace("Jack", "John")) # Hello, I am John and I am a data scientist
print(string_) # Hello, I am Jack and I am a data scientist

4. 얕은 복사(copy( )) :

fruits = {"apple", "banana", "cherry"}
fruits_copy = fruits.copy()
fruits_copy

a = {'a': 5, 'b': 4, 'c': 8}
b = a
del b['a']
print(b) # {'b': 4, 'c': 8}
print(a) # {'b': 4, 'c': 8}

a = {'a': 5, 'b': 4, 'c': 8}
b = copy.copy(a)
del b['a']
print(b)
print(a)

5. 깊은 복사(deep copy) :

  • 깊은 복사는 내부에 객체들까지 새롭게 copy 되는 것이다.
  • 완전히 새로운 변수를 만드는 것이라고 볼 수 있다.
import copy
list_var = [[1,2],[3,4]]
list_var_deepcopy = copy.deepcopy(list_var)
list_var_copy = list_var.copy()

list_var[1].append(5)

print(list_var)  # 원래 변수 [[1, 2], [3, 4, 5]]

print(list_var_deepcopy)  # deepcopy : append와 같은 메소드를 써도 값이 변경되지 않음 [[1, 2], [3, 4]]

print(list_var_copy)  # copy : 원본이 변경되었으므로 함께 변경됨 [[1, 2], [3, 4, 5]]
profile
안녕하세요, 코딩 공부하는 비전공자 취준생입니다.

0개의 댓글