text = ''' abcd efgh ijkl '''
print(text) : 출력 결과는 아래에...
abcd
efgh
ijkl
역슬래시(\)
역슬래시(\)의 기능은 바로 뒤에 나오는 문자를 특수하게 처리하라는 뜻으로 즉 \"는 문자열을 닫는 문법적 역할 " 이 아닌 "문자열 그 자체"로 쓰겠다는 뜻이다.
Ex) print("여기서 쌍따옴표는 \"라고 써주면 됩니다.") => 여기서 쌍따옴표는 "라고 써주면 됩니다.
개행문자/줄바꿈 표시
\n은 줄바꿈 표시를 의미하며 문자 count 시 하나의 문자로 계산한다.
tab 표시는 \t
다양한 문자열 처리
some_string = "python"
len(some_string) = 6
article = '''The latest jobs numbers are heralded as good news for the U.S. economy, but inflation continues to take a bite out of Americans' paychecks. Conservationists in Tanzania work to "protect the tribe while preserving the pride" of nearby lions. And the U.S. Census Bureau publishes historic documents that reflect America in 1950.'''
article.count("latest") => 1
print(len(article)) => 326(전체 글자 길이)
print(article.find("t")) => 6(t가 문장에서 몇개인가?)
print(article.replace("jobs", "occupation")) => 문장 내 jobs를 occupation으로 변경
The latest occupation numbers are heralded as good news for the U.S. economy, but inflation continues to take a bite out of Americans' paychecks. Conservationists in Tanzania work to "protect the tribe while preserving the pride" of nearby lions. And the U.S. Census Bureau publishes historic documents that reflect America in 1950.
some_string = "␣␣␣␣␣␣␣␣computer␣␣␣␣␣␣␣␣␣" => ␣ 제거하고 문자열만 출력하기 => some_string.strip('␣') => computer ※ 앞뒤로 특정 문자열을 삭제하고자 할 때 그 문자열을 ()안에 넣어준다. 공백도 가능하다
문자열 index
article = "python" => index는 0부터 시작하기에 0, 1, 2, 3, 4, 5까지임
역순으로는 왼쪽부터 -6, -5, -4, -3, -2, -1임
print(article[2]) => 결과값은 t
글자 자르기(slice) : print(article[2:4] => 결과값은 th
※ slice의 특징은 인덱스번호 2번째부터 4까지라고 했으나 실제로 자르는 건 4를 포함시키지 않는
인덱스 2,3에 해당하는
t와 h만이다.
이부분을 혼동해서는 안된다.
format 형식
중괄호({})안에 문자열을 차례차례 넣는다.
print("I have a { }, I have an { }.". format("pen", "apple"))
결과값 : I have a pen, I have an apple.
print("I have a {1}, I have an {0}.". format("pen", "apple"))
결과값 : I have a apple, I have an pen.
print("I have a {0}, I have an {0}.". format("pen", "apple"))
결과값 : I have a pen, I have an pen.
format을 이용한 소숫점 자리 표시
interest = 0.087
print(format(interest, ".2f")) ==> 소숫점 둘째짜리까지 출력 요청(반올림 기본 반영)
결과값 : 0.09
interest = 0.897
print(format(interest, ".2f")) ==> 소숫점 둘째짜리까지 출력 요청(반올림 기본 반영)
결과값 : 0.90(마지막 0은 필요없으나 소숫점 둘째짜리까지 출력 명령을 했기에 0으로 출력)
댓글남기기