문자열 인덱싱, 슬라이스, 내장함수


1. 문자열 인덱싱 또는 추출

   문자열에서 한문자를 얻기 위해서 문자열 이름뒤에 대괄호([ ])로, 

   배열같이 offset을 지정합니다.

   첫번째는 [0] 이며, 마지막은 [-1]이며, [-2], [-3] 순서로 진행됩니다.

 

>>> alphaletters = 'abcdefghijklmnopqrstuvwxyz'
>>> alphaletters[0]
'a'
>>> alphaletters[1]
'b'
>>> alphaletters[-1]
'z'
>>> alphaletters[-2]
'y'

   

   기본적으로 문자열도 immutable 변수 이기 때문에, index로 변경이

   변경이 불가능합니다.

>>> Test = 'abcde'
>>> Test[0] = 'A'  // Error 발생

   대신 나중에 설명할 내부함수 replace를 통해 변경할 수 있습니다.



2. 문자열 슬라이스

  문자열 슬라이스는 [start:end:step] 으로 표현할 수 있습니다.

  [:] : 처음부터 끝까지 전체 문자열을 추출합니다.

  [start:] : start 부터 끝까지 추출합니다.

  [:end] : 처음부터 end-1까지 추출합니다.

  [start:end] : start부터 end-1까지 추출합니다.

  [start:end:step] : step만끔 점프하면서 start에서 end-1까지 추출합니다.


>>> alphabet = 'abcdefghijklmnopqrstuvwxyz'
>>> alphabet[:]
'abcdefghijklmnopqrstuvwxyz'

>>> alphabet[20:]
'uvwxyz'

>>> alphabet[:10]
'abcdefghij'

>>> alphabet[12:15]
'mno'

>>> alphabet[-4:]
'wxyz'

>>> alphabet[18:-3]
'stuvw'

>>> alphabet[::7]
'ahov'

>>> alphabet[4:20:3]
'ehknqt'

>>> alphabet[19::4]
'tx'

>>> alphabet[:21:5]
'afkpu'

>>> alphabet[::-1]
'zyxwvutsrqponmlkjihgfedcba'



3. 문자열 내장함수

  (1) 문자열 길이 및 문자개수 세기 - len / count

       len 은 전체 문자열 길이, count는 문자열 중에 특정문자 갯수

>>> s = "abcefg"
>>> len(s) // 전체 문자열 길이
7
>>> s.count('a') // 문자열 중 'a'의 갯수
1


  (2) 문자열 나누기 - split

      split은 나누며, 나중에 정리할 리스트자료형으로 반환합니다.

>>> str = "test1, test2, test3, test4"
>>> str.split(',')
['test1', ' test2', ' test3', ' test4']


  (3) 위치 알려주기 - find / index 

      find/index 모두 위치를 반환하지만, index는 없으면 error 발생

>>> str = "Python is fun for me."
>>> str.find('i')
7
>>> str.index('i') // 찾는 문자열 존재안하면 error 발생함
7


  (4) 문자열 결합하기 - join

      join은 split과 반대의 역할을 한다. string.join(list)형태로 결합한다.

>>> list = ['test','test1','test2','test3']
>>> ",".join(list)
'test,test1,test2,test3'


  (5) 문자열 다루기 

    여러가지 문자열 함수의 예제를 들면서 보겠습니다.

>>> python_define = 'Python is a widely used high-level, general-purpose, 
interpreted, dynamic programming language.'

>>> len(python_define)
95

>>> python_define.startswith('Python')
True

>>> python_define.endswith('language.')
True

>>> python_define.find('level')
29

>>> python_define.count('level')
1

>>> python_define.isalnum()
False


  (6) 대소문자

      이번에는 대소문자를 바꾸는 방법을 한번 보겠습니다.


>>> python_define = 'Python is a widely used high-level, general-purpose, 
interpreted, dynamic programming language.'

#첫번째 단어 대문자
>>> python_define.capitalize()
'Python is a widely used high-level, general-purpose, interpreted, dynamic programming language.'

#모든 단어의 첫글자 대문자
>>> python_define.title()
'Python Is A Widely Used High-Level, General-Purpose, Interpreted, Dynamic Programming Language.'

#글자를 모두 대문자
>>> python_define.upper()
'PYTHON IS A WIDELY USED HIGH-LEVEL, GENERAL-PURPOSE, INTERPRETED, DYNAMIC PROGRAMMING LANGUAGE.'

#글자를 모두 소문자
>>> python_define.lower()
'python is a widely used high-level, general-purpose, interpreted, dynamic programming language.'

#대문자는 소문자, 소문자는 대문자,
>>> python_define.swapcase()
'pYTHON IS A WIDELY USED HIGH-LEVEL, GENERAL-PURPOSE, INTERPRETED, DYNAMIC PROGRAMMING LANGUAGE.'


  (7) 대체하기 - replace()

      문자열에서 특정 문제를 특정 문자로 바꾸는 예제를 보겠습니다.


# 문자열에서 ,를 and로 모두 바꾸는 경우
>>> python_define.replace(',', ' and')
'Python is a widely used high-level and general-purpose and interpreted and dynamic programming language.'
# 문자열에서 ,를 and로 2번만 바꾸는 경우
>>> python_define.replace(',', ' and',2)
'Python is a widely used high-level and general-purpose and interpreted, dynamic programming language.'


'프로그래밍 > Python' 카테고리의 다른 글

[Python] 자료형 (문자열)  (0) 2016.04.25
[Python] 기본자료형 (숫자형)  (0) 2016.04.20
[Python] Linux(우분투) Python 설치  (0) 2016.04.19
[Python] 기본 자료형이란?  (0) 2016.04.13
[Python] Python 철학  (0) 2016.04.13

문자열(String) 자료형


문자열 자료형이란? 일반적으로 문장, 단어, 글자 등으로 

구성된 문자들의 집합입니다.


사용법

아래와 같이 "문자열" 또는 '문자열' 이렇게 사용하면 됩니다.


>>> a = "If it rain tomorrow, blah~"
>>> b = "A"
>>> c = 'abc'


그렇다면, " " 또는 ' ' 를 쓰는 이유는 뭘까?


문자열 안에 " 이나 ' 를 넣어야 하는 경우때문에 그렇습니다.


예를 들면, " " 안에 ' ' 를 넣는 경우나 ' ' 안에 " " 를 넣는 경우에 사용할 수 있습니다.


 >>> ' I said "If I buy a car, blah~" and you said blah~' 


 >>> " I said 'If I buy a car, blah~' and you said blah~"


또 다른 방법으로는 백슬래쉬(\)로 처리하는 방법이 있습니다.


 >>> "Python is \"PERFECT\" for me."


인용부호와 Multi line을 사용하는 예시를 보겠습니다.


>>> "''''Python is fun"""
>>>"Python is fun"


아래와 같이 multi line을 위해서 ''' 또는 """ 를 사용합니다.


 >>>poem = '''There was a good man,
... Who is my father.
... He always tell me something.'''


다음으로는 문자열 연산을 보겠습니다.


결합 + 은 문자열 변수를 결합할 때 사용합니다.


>>> 'One' + 'Two' + 'Three'
'OneTwoThree'

>>> a = 'One'
>>> b = 'Two'
>>> c = 'Three'
>>> a+b+c
'OneTwoThree'


복제하기 * 는 곱하기 연산같이 복제하는데 쓰입니다.


>>> 'One' * 3
'OneOneOne'

>>> a = 'One'
>>> a * 3
'OneOneOne'


다음 포스트에서 문자열 추출 / 슬라이스 와 함께 여러 내장 함수에 대해서 알아보겠습니다.

기본자료형 - 숫자형(정수형, 실수형)


기본자료형 중 첫번째 숫자형중에서 정수형 실수형 에 대해서 정리하겠습니다.


기본적으로 Python에서는,

아래 문법과 같이 변수 이름 앞에 타입(int같은)을 지정하지 않습니다.


int a = 5;(python 에서는 이렇게 사용하지 않음)


Python에서는 아래와 같이 "변수명 = 값" 과 같은 형식으로 지정합니다.

특별히 변수명앞에 type을 지정하지 않지만, 그렇다고 type이 없는것은 아닙니다.

변수에 값을 대입후 type 함수를 이용해서 print 해보면 type은 출력됩니다.


a = 5
print("a = ",a)
print(type(a))

b = 5.5
print("b = ",b)
print(type(b))


//결과값
a =  5
<class 'int'=">
b =  5.5
<class 'float'="">



정수형, 실수형


정수형(Integer) : 값의 영역이 정수값으로 한정된 형임.

보통 5, 100, 150, 4506 등 이런 숫자형을 말합니다.

 

>>> a = 100
>>> b = 5
>>> c = 5000


실수형(real type variable) : 실수의 값을 나타내기 위한 변수.

일반적으로 소수점이 있는 숫자까지 포함합니다.


>>> a = 5.5
>>> b = -17.5
>>> c = 5236.344


8진수, 16진수


8진수 표현법


 >>> a  = 0o150 


16진수 표현법


 >>> a  = 0x4F 


8진수와 16진수는 여러가지 경우에서 종종 쓰입니다. 익숙하게 해두시면 좋습니다.

Python 설치 on Ubuntu



기본적으로 리눅스(우분투)에 Python 이 설치되어 있습니다.

아래 명령어로 버전을 확인할 수 있습니다.(2.7.4버전이네요)


$ python -V



3.X 버전을 설치하기 위해서는, 아래 명령어를 실행합니다.

아래 빨간색으로 표시된 버전을 변경하면,  해당 버전을 설치 할 수 있습니다.


$ cd /usr/local/src $ wget --no-check-certificate -N http://www.python.org/ftp/python/3.5.1/Python-3.5.1.tgz $ tar xzf Python-3.5.1.tgz $ cd Python-3.5.1 $ ./configure $ make $ make altinstall


$ mv /usr/bin/python /usr/bin/python_bk       // 현재 설치된 폴더를 backup 합니다.


$ cp /usr/local/bin/python3.5 /usr/bin/python   // 설치한 3.5.1 버전을 python 폴더에 복사합니다. 


$ python -V    // 설치된 버전을 확인합니다. 


'프로그래밍 > Python' 카테고리의 다른 글

[Python] 자료형 (문자열)  (0) 2016.04.25
[Python] 기본자료형 (숫자형)  (0) 2016.04.20
[Python] 기본 자료형이란?  (0) 2016.04.13
[Python] Python 철학  (0) 2016.04.13
[Python] Python IDE 소개 및 개발 환경  (0) 2016.04.10

Python의 기본 자료형


프로그래밍을 공부하다 보면 항상 첫번째로 나오는것이 자료형인거 같습니다.

자료형만 자유롭게 쓸 수 있다면, 그 언어의 기본이상을 하는거죠.


사실 python의 경우 자료형이 기본 C, Java와 비슷하면서도 큰 차별점이 있습니다.


기본 자료형의 종류


1. 숫자형

2. 문자열 자료형

3. 리스트 자료형

4. 튜플 자료형

5. 딕셔너리 자료형

6. 집합 자료형

+로 자료형들의 특징, 저장공간의 특징등을 블로그에 정리할 예정입니다.

'프로그래밍 > Python' 카테고리의 다른 글

[Python] 기본자료형 (숫자형)  (0) 2016.04.20
[Python] Linux(우분투) Python 설치  (0) 2016.04.19
[Python] Python 철학  (0) 2016.04.13
[Python] Python IDE 소개 및 개발 환경  (0) 2016.04.10
[Python] Python 설치하기  (0) 2016.04.08

Python 철학

본격적으로 설명 나가기전에, 왜 Python인가 하는 의문을 가지는 사람도 있을것입니다.

사실 저도 Python을 접하기전에 "왜?" 가 제일 궁금했었습니다.

아래와 같이 "import this" 입력하면 파이썬 철학이 출렵됩니다.


저런 철학적 이유 때문에 Python을 사용하는거겠죠.


>> import this

//출력결과
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!






'프로그래밍 > Python' 카테고리의 다른 글

[Python] Linux(우분투) Python 설치  (0) 2016.04.19
[Python] 기본 자료형이란?  (0) 2016.04.13
[Python] Python IDE 소개 및 개발 환경  (0) 2016.04.10
[Python] Python 설치하기  (0) 2016.04.08
[Python] Python 이란?  (0) 2016.04.04

Python IDE


개인적인 추천 및 특정 blog 내용이니, 참고만 하시면 됩니다.

앞으로의 해당 블로그는 PyCharm으로 진행할 예정입니다.


그래도 일반적으로 아래와 같은 Eclipse, PyCharm등 IDE를 많이 사용합니다.


앞으로 블로그를 진행할 PyCharm 설치방법에 대해 간단히 정리하자면,

Link : https://www.jetbrains.com/pycharm/download/ 에서 

Professional 또는 Community 버전으로 다운받으면 됩니다.


Professional 은 유료 License 이며, Community는 무료 License입니다.


학생의 경우 https://www.jetbrains.com/student/ 링크와 함께 무료정책이

있습니다. Email address나 ISIC 학생증이 있으면 됩니다.


해당 관련 정책은 https://www.jetbrains.com/store/#edition=discounts 에 있습니다.







Eclipse with PyDev


It's hard to write anything about open source integrated development environments without covering Eclipse, which has a huge developer community and countless plugins available allowing you to customize it to meet nearly any need you can imagine. But this kitchen sink approach is also one of Eclipse's downsides. Many criticize it as bloated, and performance on low spec systems certainly can be an issue.

That said, if you're coming to Python from a background in a different language, particularly Java, Eclipse may already be your go to IDE. And if you make use of its many features, you may find life without them difficult.

PyDev adds a huge number of features to Eclipse, far beyond simple code highlighting. It handles code completion, integrates Python debugging, adds a token browser, refactoring tools, and much more. For those working with the popular Django Python web framework, PyDev will allow you to create new Django projects, execute Django actions via hotkeys, and use a separate run configuration just for Django.

Eclipse and PyDev are both made available under the Eclipse Public License.




Eric


Eric is my personal favorite IDE for Python editing. Named after Monty Python's Eric Idle, Eric is actually written in Python using the Qt framework.

Eric makes use of Scintilla, a source code editing component which is used in a number of different IDEs and editors which is also available as the stand-aloneSciTE editor.

The features of Eric are similar to other IDEs: brace matching, code completion, a class browser, integrated unit tests, etc. It also has a Qt form preview function, which is useful if you're developing a Qt GUI for your application, and I personally like the integrated task list function.

I've heard some criticisms of Eric's documentation, which primarily being delivered through a massive PDF does leave something to be desired, but if you take the time to learn it, I find Eric to be a lighweight yet full-featured programming environment.

Eric is made available under the GPL version 3.




PyCharm


PyCharm is another popular Python editor and rounds out my top three. Pycharm is a commercial product, but the makers also offer a community edition which is free and open source under the Apache 2.0 license.

PyCharm features pretty much everything one might hope for in an IDE: integrated unit testing, code inspection, integrated version control, code refactoring tools, a variety of tools for project navigation, as well as the highlighting and automated completion features you would expect with any IDE.

To me, the main drawback of PyCharm is its open core model. Many of PyCharm's advanced features are not available under an open source license, and for me, that's a deal breaker. However, if you're not looking to use the more advanced features included in the closed source verion, having the features left out may leave PyCharm as a lighter weight choice for Python editing.



Window command 개발

명령어 창에 Python을 치면 개발할 수 있는 환경이 됩니다.

만약 안된다면 환경변수를 한번 확인해보세요.



'프로그래밍 > Python' 카테고리의 다른 글

[Python] Linux(우분투) Python 설치  (0) 2016.04.19
[Python] 기본 자료형이란?  (0) 2016.04.13
[Python] Python 철학  (0) 2016.04.13
[Python] Python 설치하기  (0) 2016.04.08
[Python] Python 이란?  (0) 2016.04.04

Python 설치하기


1. Install Python on Windows!

 (1) 공식 hompage 접속(http://www.python.org)



 (2) 위의 Download 페이지를 클릭!

     (3.X 버전과 2.X 버전이 있음, 최신은 3.X버전이나 시스템에 2.X버전으로 설치되어있는 

     경우도 있어 둘다 지원하고 있음, 차이는 문법차이외에도 많은 차이점이 있으니, 

     2.X 버전이 특별히 필요하지 않는 경우는 3.X버전 설치할것!)

 


 (3) 클릭해서 들어가면 아래 File 항목에 OS별 / 소스 Download가 있음

        Windows x86-64 executable installer를 다운로드 후 실행하세요.


'프로그래밍 > Python' 카테고리의 다른 글

[Python] Linux(우분투) Python 설치  (0) 2016.04.19
[Python] 기본 자료형이란?  (0) 2016.04.13
[Python] Python 철학  (0) 2016.04.13
[Python] Python IDE 소개 및 개발 환경  (0) 2016.04.10
[Python] Python 이란?  (0) 2016.04.04

+ Recent posts