๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Python

[Python] ๋ฌธ์ž์—ด ์ธ๋ฑ์‹ฑ๊ณผ ์Šฌ๋ผ์ด์‹ฑ

by ์ฝ”๋”ฉํ•˜๋Š” ๋ถ•์–ด 2021. 2. 5.
๋ฐ˜์‘ํ˜•

์ธ๋ฑ์‹ฑ(Indexing)์ด๋ž€ ๋ฌด์—‡์ธ๊ฐ€๋ฅผ '๊ฐ€๋ฆฌํ‚จ๋‹ค'๋Š” ์˜๋ฏธ์ด๊ณ ,

์Šฌ๋ผ์ด์‹ฑ(slicing)์€ ๋ฌด์—‡์ธ๊ฐ€๋ฅผ '์ž˜๋ผ๋‚ธ๋‹ค'๋Š” ์˜๋ฏธ์ด๋‹ค.

 

 

โ–ถ ๋ฌธ์ž์—ด ์ธ๋ฑ์‹ฑ

>>> a = "Life is too short"

>>> a = "Life is too short"
>>> a[3]
'e'

โ˜…๋ฌธ์ž์ผ๋• '' ๊ฐ€ ๋ถ™๋Š”๋‹ค๊ณ  ํ•จ

 

 

 

โ–ถ ๋ฌธ์ž์—ด ์ธ๋ฑ์‹ฑ ํ™œ์šฉํ•˜๊ธฐ

>>> a = "Life is too short"
>>> a[0]
'L'
>>> a[12]
's'
>>> a[-1]
't'

a[-1]์€ ๋’ค์—์„œ๋ถ€ํ„ฐ ์„ธ์–ด ์ฒซ ๋ฒˆ์งธ๊ฐ€ ๋˜๋Š” ๋ฌธ์ž๋ฅผ ๋งํ•œ๋‹ค.

โ€‹

 

>>> a[-0]
'L'

a[-0]์€ a[0]๊ณผ ๋˜‘๊ฐ™๋‹ค.

 

 

>>> a[-2]
'o'
>>> a[-5]
'y'

 

 

 

โ–ถ ๋ฌธ์ž์—ด ์Šฌ๋ผ์ด์‹ฑ

-๋‹จ์ˆœํ•œ ๋ฐฉ๋ฒ•

>>> a : "Life is too short"
>>> b = a[0] + a[1] + a[2] + a[3]
>>> b
'Life'

 

 

-์Šฌ๋ผ์ด์‹ฑ ๊ธฐ๋ฒ•

>>> a : "Life is too short"
>>> a[0:4]
'Life'

0๋ถ€ํ„ฐ 4๊นŒ์ง€์˜ ๋ฌธ์ž๋ฅผ ๋ฝ‘์•„๋‚ธ๋‹ค๋Š” ๋œป (0 <= a < 3)

โ˜…[์‹œ์ž‘ ๋ฒˆํ˜ธ:๋ ๋ฒˆํ˜ธ] ์—์„œ ๋๋ฒˆํ˜ธ์— ํ•ด๋‹นํ•˜๋Š”๊ฑด ํฌํ•จํ•˜์ง€ ์•Š๋Š”๋‹ค.

 

 

-[์‹œ์ž‘ ๋ฒˆํ˜ธ:๋ ๋ฒˆํ˜ธ] ์—์„œ ๋ ๋ฒˆํ˜ธ๋ฅผ ์ƒ๋žตํ•˜๋ฉด ์‹œ์ž‘๋ฒˆํ˜ธ๋ถ€ํ„ฐ ๊ทธ ๋ฌธ์ž์—ด์˜ ๋๊นŒ์ง€ ๋ฝ‘์•„๋‚ธ๋‹ค.

>>> a[12:]
'short'

 

 

-[์‹œ์ž‘ ๋ฒˆํ˜ธ:๋ ๋ฒˆํ˜ธ] ์—์„œ ์‹œ์ž‘ ๋ฒˆํ˜ธ๋ฅผ ์ƒ๋žตํ•˜๋ฉด ๋ฌธ์ž์—ด์˜ ์ฒ˜์Œ๋ถ€ํ„ฐ ๋ ๋ฒˆํ˜ธ๊นŒ์ง€ ๋ฝ‘์•„๋‚ธ๋‹ค.

>>> a[:4]
'Life'

 

 

-[์‹œ์ž‘ ๋ฒˆํ˜ธ:๋ ๋ฒˆํ˜ธ] ์—์„œ ์‹œ์ž‘ ๋ฒˆํ˜ธ์™€ ๋ ๋ฒˆํ˜ธ๋ฅผ ์ƒ๋žตํ•˜๋ฉด ๋ฌธ์ž์—ด์˜ ์ฒ˜์Œ๋ถ€ํ„ฐ ๋๊นŒ์ง€๋ฅผ ๋ฝ‘์•„๋‚ธ๋‹ค.

>>> a[:]
'Life is too short'

 

 

>>> a[8:-6]
'too'

์—ฌ๊ธฐ์„œ [-6]์€ ํฌํ•จํ•˜์ง€ ์•Š๋Š”๋‹ค.

 

 

 

โ–ถ ์Šฌ๋ผ์ด์‹ฑ์œผ๋กœ ๋ฌธ์ž์—ด ๋‚˜๋ˆ„๊ธฐ

>>> a = "20010331Rainy"
>>> date = a[:8]
>>> weather = a[8:]
>>> date
'20010331'
>>> weather
'Rainy'

a[:8]์€ a[8]์ด ํฌํ•จ๋˜์ง€ ์•Š๊ณ , a[8:]์€ a[8]์„ ํฌํ•จํ•˜๊ธฐ ๋•Œ๋ฌธ์— 8์„ ๊ธฐ์ค€์œผ๋กœ ๋‘ ๋ถ€๋ถ„์„ ๋‚˜๋ˆŒ ์ˆ˜ ์žˆ๋‹ค.

๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€