728x90

파이썬 기초를  아주 많이 쉽게 간추려서 올려 드리고있습니다. 완전 기초 입문자를 위한 자료입니다.

문자열 자료형

파이썬에서 문자열 객체는 따옴표를 이용하여 생성합니다. 

 

홑따옴표(' … ')  쌍따옴표(" … ")  홑따옴표 세 개(''' … ''')  쌍따옴표 세 개(""" … """)

>>> s ='Python is great!'
>>> s ="Python is great!"
>>> s = '''Python is great!'''
>>> s = """Python is great!"""
>>> print(s)
Python is great!

또한 역슬래쉬(\)를 이용하여 긴 문자열 생성을 할 수 있습니다. 

>>> sentence = 'Python is the \
most popular programming \
language in these days.'
>>> print(sentence)
Python is the most popular programming language in these
days.

문자열 안에 홑따옴표 혹은 쌍따옴표를 쓰고싶을때의 방법도 알려드리겠습니다. 

say
'hello' to mom.
4
>>> a = 'say 'hello' to mom
'
SyntaxError: invalid syntax
>>> b = "say 'hello' to mom
"
>>> c = '''say 'hello' to mom
'''
>>> d = """say 'hello' to mom
"""
>>> print(d)
say 'hello' to mom
>>> s = 'say "hello" to mom
'
>>> s = '''say "hello" to mom
'''
>>> s = """say "hello" to mom
"""
>>> print(s)
say "hello" to mom

s = """say "hello" to '
mom
'"""
>>> print(s)
say "hello" to 'mom'

긴 문장을 쓰고싶을때 !

# letter to Alice
print('''Dear Alice,
How are you?
I am busy to study programming this vacation.
Say hello to your parents.
Sincerely,
Bob''')

 

문자열 객체의 특징

 - immutable하다. 

 - 순서가 있는 자료형으로 인덱싱을 이용할수 있다. 

인덱스에 있는 값들을 불러올수 있는 자료형입니다. 

 

문자열 연결하기 (+) 

문자열 반복하기는 (*) 를 사용합니다

예를들어서  a =hello, a*3 를 쓰면 문자열을 3회 반복하여 출력이 됩니다. 'hellohellohello' 

문자열 길이/포함 관계

문자열 길이 - len() 내장함수입니다. 

subject='programming'

len(subject)

11 (subject의 문자열길이를 나타냅니다. )

문자열 포함 - in, not in 연산자

>>> 'r' in subject
True
>>> 'gram' in subject
True
>>> 'abcd' not in subject
True
더보기

문자열 객체에 사용할 수 있는 메소드 확인방법 . 문자열.메소드() 형태로 사용한다. 

>>> dir(str)

['__add__', '__class__', ……'__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

문자열 메소드 이용하기

 

728x90

'Language > python' 카테고리의 다른 글

numpy -인덱싱 / 슬라이싱  (0) 2022.06.21
numpy - ndarray 데이터 형태 바꿔보기  (0) 2022.06.21
numpy- 기초  (0) 2022.06.21
파이썬 기초-3(입출력문)  (0) 2022.06.15
파이썬 기초 -1  (0) 2022.06.14
728x90

객체와 변수 

객체(Object)

  • 메모리에 저장된 자료를 '객체'라고 부른다.
  • 모든 객체는 자료형 (data types)을 갖는다. 
  • 모든 객체는 고유 id 를 갖는다.
  • 객체를 저장한 공간을 변수(Variable)라고 하고 변수명(variable name)으로 객체에 접근할수 있다. 

객체생성하는법

Ex) a = 100

 

변수명 만들기

  • 변수명은 영어 소문자, 대문자, 숫자,_(underscore)로만 구성한다.
  • 변수명은 숫자로 시작할 수없다. 
  • 대소문자를 구분한다. 즉, data 와 Data는 다른변수이다.
  • 변수명은 한글도 가능하다.
  • 키워드(keyword)를 변수명으로 사용하면 안된다.

>>>number = 5
>>>score = 90
>>>python_score = 95
>>>_score =100
>>>math-score =90 #syntax 에러. 특수 기호는 _만 가능하다.
>>> math1 = 80
>>> 1math = 80 # syntax 에러. 숫자로 시작할 수 없다
>>> 학생수 = 50 # 한글 변수명도 가능함

객체 삭제하기

 del 을 이용하면 객체를 삭제할수 있다. 

>>> data = 100
>>> print(data)
100
>>> del data
>>> print(data)
Traceback (most recent call last):
File "<pyshell#13>", line 1, in <module>
print(data)
NameError: name 'data' is not defined

자료형

파이썬 자료형(data types)

수치 자료형 - int(정수),float(실수), Complex(복소수)

부울 자료형 - bool(True/False)

군집으로 다루는 자료형

-str(문자열)

-list(리스트)

-tuple(튜플)

-set(집합)

-dict(사전)

 

 

정수형(int) -  자료는 10진수, 2진수,8진수, 16진수가 있다. 

type(변수명) :변수의 자료형을 알려준다. 

id(변수명): 변수의 식별자를 알려준다.

>>> score = 23
>>> print(score)
23
>>> type(score)
<class 'int'>
>>> id(score)
1525430384

실수형(float) 

소수점을 포함하는 수이다. 

>>> data = 1.5
>>> print(data)
1.5
>>> type(data)
<class 'float'>
>>> id(data)
51659472

복소수형(complex) - 복소수형은 실수부와 허수부로 표현한다. 허수부 뒤에는 j또는 J를 붙인다. 

>>> x = 3 + 5j
>>> print(x)
(3+5j)
>>> type(x)
<class 'complex'>
>>> id(x)
54137944

부울형 (bool) - 파이썬의 부울형은 참/거짓을 나타내는 True/False 의 두값만을 갖는다.

>>> a = True
>>> b = False
>>> type(a)
<class 'bool'>
>>> type(b)
<class 'bool'>
>>> x = 1
>>> y = x > 0
>>> print(y)
True
>>> type(y)
<class 'bool'>

문자열 (str) - 따옴표를 이용하여 표현한다. 

>>> name = 'Alice' # 홑따옴표
>>> print(name)
Alice
>>> type(name)
<class 'str'>
>>> id(name)
59750720
>>> city = 
"Seoul, Korea" # 쌍따옴표
>>> print(city)
Seoul, Korea
>>> language = '''python''' # 홑따옴표 세 개
>>> print(language)
Python
>>> w = """Python is widely used""" # 쌍따옴표 세 개
>>> print(w)
Python is widely used

리스트(list) -대괄호[] 로 표현한다. 여러개의 자료들을 모아서 저장해야 하는 경우에 사용한다. 

>>> scores = [80, 90, 85, 93, 78]
>>> print(scores)
[80, 90, 85, 93, 78]
>>> type(scores)
<class 'list'>
>>> id(scores)
57012752

튜플(tuple) - 괄호() 로 표현한다. 리스트처럼 여러 개의 자료를 저장할수 있다. 

>>> data = (3,6,5,9)
>>> print(data)
(3, 6, 5, 9)
>>> type(data)
<class 'tuple'>
>>> id(data)
58257504

집합(set) - {} 로 표현한다.  중복되지 않는 여러 개의 자료들을 모아서 저장해야 하는 경우에 집합을 사용한다. 

>>> primes = {7,17,3,5,7,19}
>>> print(primes)
{17, 19, 3, 5, 7}
>>> type(primes)
<class 'set'>
>>> id(primes)
57212120

사전(dict)  - 키(key) 와 값(value) 의 쌍으로 구성되는 집합의 일종이다. 

예) 1반 35명, 2반 32명,3반 30명, 4반 33명의 학생들이 있다면 사전을 이용하여 다음과 같이 표현할수 있다.

>>> count = {1:35, 2:32, 3:30, 4:33}
>>> print(count)
{1: 35, 2: 32, 3: 30, 4: 33}
>>> type(count)
<class 'dict'>
>>> id(count)
52998272

주석은 #으로 표현되고 길게 적고싶으면 ''' ''' 아니면 """ """ 을 사용하면 된다. 

단축키는 ctrl +shift + / 을 누르면된다.

#이렇게 적으면 코드로 읽지 않는다. 
""" 프로젝트 1.
작성자 : 홍길동
완성일 : 2016. 07. 31
프로젝트 버전 : 0.01
이 프로젝트는 파이썬 버전 3을 이용하였음 """
print('start of the program')
# 주요 코드 시작 부분
print('......')
"""
…… 
""" – 쌍따옴표 3개로 작성한 부분을 docstring 이라고 한다.
docstring은 함수, 클래스, 모듈 등을 작성할 때 유용하다
728x90

'Language > python' 카테고리의 다른 글

numpy -인덱싱 / 슬라이싱  (0) 2022.06.21
numpy - ndarray 데이터 형태 바꿔보기  (0) 2022.06.21
numpy- 기초  (0) 2022.06.21
파이썬 기초-3(입출력문)  (0) 2022.06.15
파이썬 기초 -2  (0) 2022.06.15

+ Recent posts