Skip to content

Latest commit

 

History

History
130 lines (94 loc) · 5.43 KB

File metadata and controls

130 lines (94 loc) · 5.43 KB

Chapter 5. Sequenses: Strings, Lists, and Files

핵심 골자

  • String에 대한 개념
  • List와 String의 차이 ( Mutable VS Immutable )
  • Encoding System
  • String 처리 방법
  • String Formatting
  • File Processing

1. String에 대한 개념

기본 정의

A Sequence of characters.

Imgur

이렇기 때문에 List의 Indexing 방법과 비슷하게 다룰수 있다.

text = "Hello Bob"
#Indexing 하기 
text[0]    #>>> "H"
text[-1]   #>>> "b"
text[0:2]  #>>> "He"
###cf _____ 이 부분은 사실 slice라는 객체임    
text[0::3] #>>> "HlB"

그 외의 데이터를 조작하는 방법으로는 아래와 같은 것들이 존재한다.

"spam" + "eggs" #>>> "spameggs"
"spam" * 5      #>>> "spamspamspamspamspam"
len("spam")     #>>> 4
for ch in "spam":
	print(ch, end=" ") #>>> "s p a m"

list의 조작방식과 거의 흡사하다. 그렇다면 차이점이 뭘까?

2. List와 String의 차이

리스트는 Mutable vs string은 Immutable. 이에 대한 차이는 바로 아래 예제로 확연히 알 수 있다.

myList = [34, 26, 15, 10]
myList[2] #>>> 15
myList[2] = 0 
myList[2] #>>> [34, 26, 0, 10]

myString = "Hello World"
myString[2] #>>> l
myString[2] = 'z' #>>> ERROR!

한번 만들어지면 절대 불변한다. 근데 파이썬은 왜 이렇게 설계했을까? -> Quora의 답변

  1. Make strings immutable and require the keys to be immutable. This is what python does.

  2. Deep-copy the keys before placing objects into dictionaries, this is kind of what C++'s std::map and std::unordered_map do. This goes against python philosophy of copying references rather than values. Never performing a deep-copy except here is surprising, and it is bad idea to surprise programmers.

  3. the storage for a string is fixed at construction and never alters. Obviously that makes handling strings a lot simpler. Multiple large strings (e.g. genomic sequence data) with the same value can be stored efficiently by pointing at the same stored value.

3. Encoding System

모든 character 시스템에는 Encoding이 딸려 있음. 컴퓨터는 숫자만 처리할 수 있는데, 문자를 처리할 수 있게 된건, 문자와 숫자 사이를 매칭시켜주는 Encoding 표가 있기 때문이다.

이러한 표가 컴퓨터끼리 통일되어 있지 않으면, 우린 서로 어떤 글을 쓰고 있는지 알아 볼 수 없게 된다. 옛날에는 위와 같은 아스키 코드를 이용했으나, 현대에 와서는 UTF-8이 기본 포맷.

4. String 처리 방법

s = " Hello i'm Sang jae "

function 예제 결과
s.capitalize() s.capitalize() " hello i'm sang jae "
s.center(width) s.center(30) " Hello i'm Sang jae "
s.find(sub) s.find("Sang") 11
s.join(list) " ".join(["hello",'im','sang','jae']) "hello im sang jae"
s.ljust(width) s.ljust(30) " Hello i'm Sang jae "
s.lower() s.lower() " hello i'm sang jae "
s.lstrip() s.lstrip() "Hello i'm Sang jae "
s.replace(oldsub, newsub) s.replace("Hello","hi,") " hi, i'm Sang jae "
s.rfind(sub) s.rfind("Sang") 11
s.rjust(width) s.rjust(30) " Hello i'm Sang jae "
s.rstrip() s.rstrip() " Hello i'm Sang jae"
s.split() s.split() ['Hello', "i'm", 'Sang', 'jae']
s.title() s.title() " Hello I'M Sang Jae "
s.upper() s.upper() " HELLO I'M SANG JAE "

5. string format

pyformat을 같이 읽어보자. 설명이 완벽하다

6. 파일 프로세싱

우리는 엄청나게 긴 문자열을 다룰 때는 대부분 text파일을 만들어서 거기에 담아 쓰곤 한다. 파일을 다루는 방법은 매우 간단하다

<variable> = open(<name>, <mode>)

name에는 파일의 위치, mode 에는 r 혹은 w로, 파일을 읽을것인지 수정할 것인지 결정. variable에는 파일 object가 들어간다.

# reading 모드
infile = open("numbers.txt", "r")
infile.read() # Returns the entire remaining contents of the file as a single string
infile.readline() # Returns the next line of the file
infile.readliens() # Returns a list of the remaining lines in the file.
infile.close()

# writing 모드
with open("output.txt", "w") as f:
    f.write("안녕")
    f.writelines(["컴싸","간만이다야"])

하지만 위의 방식보다 좀 더 깔끔한 코드는 보통은 with 구문을 이용한다.

with open("numbers.txt", 'r') as f:
    f.read()