print("hello") #출력:hello
print('hello') #출력:hello
print("hello 'world'") #출력: hello 'world'
print('hello "world"') #출력: hello "world"
print("hello" + "world") #출력: helloworld
print("hello","world") #출력: hello world
print("hello" "world") #출력: helloworld
파이썬은 문자열을 ' ' 또는 " "로 감싸서 표현합니다.
이때 저 기호 자체를 문자열로 만들고싶다면 위 코드의 3,4번째같이 사용하면 됩니다.
+를 이용하여 두 문자열을 이어붙일수 있습니다.
,를 사용해서 이어붙이면 사이에 자동으로 공백 한칸이 추가됩니다.
print('hello', end='%^&')
print("world")
#출력 : hello%^&world
print('hello', 'world', sep='-')
#출력: hello-world
f = open('test.txt', 'w')
print('hello world', file=f)
f.close()
#test.txt에 hello world가 저장됨
import sys
print('MyError', file=sys.stderr)
#표준에러처리로 MyError가 발생함
end 인자를 사용하면 print함수 마지막 효과를 변경할 수 있습니다. (기본값은 개행)
sep 인자를 사용하면 콤마로 구분된 문자열을 다르게 결합할 수 있습니다. (기본값은 공백)
file 인자를 사용하면 출력 결과를 파일, 표준에러처리로 보낼 수 있습니다.
i = 123
f = 3.14
s = 'Hello'
print('i: %d, f: %f, s: %s' % (i, f, s))
#출력 : i: 123, f: 3.140000, s: Hello
C언어식 표현방법도 가능합니다.
이스케이프 문자
print("escape \'test") #출력 : escape 'test
복제하기: *
print("ha" * 3)
#출력: hahaha
문자 추출: []
string="abcdefg"
print(string[0]) #출력:a
print(string[1]) #출력:b
print(string[-1]) #출력:g
print(string[-2]) #출력:f
가장 왼쪽은 0, 오른쪽으로 1,2,3...
가장 오른쪽은 -1, 왼쪽으로 -2,-3,-4...
슬라이스: [start:end:step]
start는 시작 오프셋(맨 처음을 의미하는것이 아님. 이 자리에 들어오는 숫자가 시작지점이라는 뜻)을 의미,
end는 끝 오프셋(맨 끝 말하는것이 아닌, 이 자리에 들어오는 숫자가 끝 지점이라는뜻)을 의미,(실제로는 이것 바로 앞까지를 의미함)
step은 옵션.
이들 중 일부 생략 가능
- [ : ] 처음부터 끝까지 전체 시퀀스를 추출한다
- [start:] start오프셋부터 끝까지 시퀀스를 추출한다
- [:end] 처음부터 (end-1)오프셋까지 시퀀스를 추출한다
- [start : end] start오프셋부터 (end-1) 오프셋까지 시퀀스를 추출한다
- [start:end:step] step만큼 문자를 건너뛰면서, start 오프셋부터 (end-1)오프셋까지 시퀀스를 추출한다.
string="abcdefg"
print(string[1:2]) #출력: b
print(string[3::2]) #출력: df
문자열 길이: len()
print(len("abc")) #출력: 3
스페이스와 줄바꿈도 포함된 길이가 나옵니다.
문자열 나누기: split()
string="ca t, do g, compu ter"
print(string.split()) #출력: ['ca', 't,', 'do', 'g,', 'compu', 'ter']
print(string.split(",")) #출력: ['ca t', ' do g', ' compu ter']
a=string.split()
print(a[1]) #출력: t,
특정 구분자를 기준으로 하나의 문자열을 작은 문자열들의 리스트로 나누기 위해서 문자열 내장함수 split()을 사용합니다.
구분자를 지정하지 않으면 split()은 문자열에 등장하는 공백 문자(줄바꿈,스페이스,탭)을 사용합니다.
문자열로 결합하기: join()
join()함수는 split()함수의 반대입니다.
join()함수는 문자열 리스트를 하나의 문자열로 결합합니다.
string_list=['hello','world','python']
join_string='#'.join(string_list)
print(join_string) #출력: hello#world#python
문자열 정렬( center(), ljust(), rjust() )
string="hello world"
print(string.center(30)) #출력: hello world
print(string.ljust(30)) #출력:hello world
print(string.rjust(30)) #출력: hello world
지정한 공간에서 정렬함
center,ljust,rjust가 있음
대체하기: replace()
string="hello world hello world hello world"
print(string.replace("hello","hi",2)) #출력:hi world hi world hello world
인자로 바꿀 문자열, 대체할 새 문자열, 바꿀 문자열에 대한 횟수를 입력합니다.
횟수를 생략하면 모든 문자열에대해서 바꿉니다.
그 외 다양한 함수
string="hello world"
print(string.startswith("he")) #출력: True
startswith() : 특정 문자로 시작하는지 여부를 출력해줌
string="hello world"
print(string.endswith("orld")) #출력: True
endswith() : 특정 문자로 끝나는지 여부를 출력해줌
string="is is is is"
print(string.find("is")) #출력: 0
find(): 특정 문자가 첫번째로 나오는 오프셋을 출력해줌
string="is is is is"
print(string.rfind("is")) #출력: 9
rfind(): 특정 문자가 마지막으로 나오는 오프셋을 출력해줌
string="is is is is"
print(string.count("is")) #출력: 4
count(): 특정 문자가 몇 번 나오는지 출력해줌
string="this is *"
print(string.isalnum()) #출력: False
Ironman="ILoveYou3000"
print(Ironman.isalnum()) #출력: True
Ironman="I Love You3000"
print(Ironman.isalnum()) #출력: False
isalnum(): 글자와 숫자로만 이루어져 있는가를 출력해줌 (띄어쓰기도 안됨)
string="hello world this is PYTHON..!.."
print(string.strip('.')) #출력: hello world this is PYTHON..!
print(string.capitalize()) #출력: Hello world this is python..!..
print(string.title()) #출력: Hello World This Is Python..!..
print(string.upper()) #출력: HELLO WORLD THIS IS PYTHON..!..
print(string.lower()) #출력: hello world this is python..!..
print(string.swapcase()) #출력: HELLO WORLD THIS IS python..!..
strip(): 양끝에서 특정 시퀀스를 삭제
capitalize(): 첫 단어를 대문자로
title(): 모든 단어의 첫글자를 대문자로
upper(): 모두 대문자로
lower(): 모두 소문자로
swapcase(): 대문자는 소문자로, 소문자는 대문자로
'Python' 카테고리의 다른 글
[Python] 라인 유지하기: \ (0) | 2022.09.23 |
---|---|
[Python] 셋(Set) (0) | 2022.09.23 |
[Python] 딕셔너리(딕트) (0) | 2022.09.09 |
[Python] 튜플(tuple) (0) | 2022.09.09 |
[Python] 리스트(List) (0) | 2022.09.08 |