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

[Python] ๋ฌธ์ž์—ด ๊ด€๋ จ ํ•จ์ˆ˜

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

๋ฌธ์ž์—ด ์ž๋ฃŒํ˜•์€ ์ž์ฒด์ ์œผ๋กœ ํ•จ์ˆ˜๋ฅผ ๊ฐ€์ง€๊ณ  ์žˆ๋‹ค. ๋‹ค๋ฅธ ๋ง๋กœ๋Š” ๋ฌธ์ž์—ด ๋‚ด์žฅ ํ•จ์ˆ˜๋ผ๊ณ  ํ•œ๋‹ค.

์ด ๋‚ด์žฅ ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•˜๋ ค๋ฉด ๋ฌธ์ž์—ด ๋ณ€์ˆ˜ ์ด๋ฆ„ ๋’ค์— '.'๋ฅผ ๋ถ™์ธ ๋‹ค์Œ์— ํ•จ์ˆ˜ ์ด๋ฆ„์„ ์จ์ฃผ๋ฉด ๋œ๋‹ค.

 

 

-๋ฌธ์ž ๊ฐœ์ˆ˜ ์„ธ๊ธฐ (count)

>>> a = "hobby"
>>> a.count('b')
2

๋ฌธ์ž์—ด ์ค‘ ๋ฌธ์ž b์˜ ๊ฐœ์ˆ˜๋ฅผ ๋Œ๋ ค์ค€๋‹ค.

 

 

-์œ„์น˜ ์•Œ๋ ค์ฃผ๊ธฐ 1 (find)

>>> a = "Python is the best choice"
>>> a.find('b')
14   ← ๋ฌธ์ž์—ด์—์„œ b๊ฐ€ ์ฒ˜์Œ ๋‚˜์˜จ ์œ„์น˜
>>> a.find('k')
-1   ← ์ฐพ๋Š” ๋ฌธ์ž๋‚˜ ๋ฌธ์ž์—ด์ด ์กด์žฌํ•˜์ง€ ์•Š๋Š”๋‹ค๋ฉด -1์„ ๋ฐ˜ํ™˜ํ•จ

 

 

-์œ„์น˜ ์•Œ๋ ค์ฃผ๊ธฐ 2 (index)

>>> a = "Life is too short"
>>> a.index('t')
8
>>> a.index('k')
Traceback (most recent call last):   ← k๊ฐ€ ์—†๊ธฐ ๋•Œ๋ฌธ์— ์˜ค๋ฅ˜ ๋ฐœ์ƒ
  File "<stdin>", line 1, in <module>
ValueError: substring not found

 

 

-๋ฌธ์ž์—ด ์‚ฝ์ž… (join)

>>> ",".join('abcd')
'a,b,c,d'

join ํ•จ์ˆ˜๋Š” ๋ฌธ์ž์—ด๋ฟ๋งŒ ์•„๋‹ˆ๋ผ ์•ž์œผ๋กœ ๋ฐฐ์šธ ๋ฆฌ์ŠคํŠธ๋‚˜ ํŠœํ”Œ๋„ ์ž…๋ ฅ์œผ๋กœ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค.

>>> ",".join(['a', 'b', 'c', 'd'])
'a,b,c,d'

 

 

-์†Œ๋ฌธ์ž๋ฅผ ๋Œ€๋ฌธ์ž๋กœ ๋ฐ”๊พธ๊ธฐ (upper)

>>> a = "hi"
>>> a.upper()
'HI'

๋ฌธ์ž์—ด์ด ์ด๋ฏธ ๋Œ€๋ฌธ์ž๋ผ๋ฉด ์•„๋ฌด ๋ณ€ํ™”๋„ ์ผ์–ด๋‚˜์ง€ ์•Š๋Š”๋‹ค.

 

 

-๋Œ€๋ฌธ์ž๋ฅผ ์†Œ๋ฌธ์ž๋กœ ๋ฐ”๊พธ๊ธฐ (lower)

>>> a = "HI"
>>> a.lower()
'hi'

 

 

-์™ผ์ชฝ ๊ณต๋ฐฑ ์ง€์šฐ๊ธฐ (lstrip)

>>> a = " hi "
>>> a.lstrip()
'hi '

๋ฌธ์ž์—ด ์ค‘ ๊ฐ€์žฅ ์™ผ์ชฝ์— ์žˆ๋Š” ํ•œ ์นธ ์ด์ƒ์˜ ์—ฐ์†๋œ ๊ณต๋ฐฑ๋“ค์„ ๋ชจ๋‘ ์ง€์šด๋‹ค. lstrip์—์„œ l์€ left๋ฅผ ์˜๋ฏธํ•œ๋‹ค.

 

 

-์˜ค๋ฅธ์ชฝ ๊ณต๋ฐฑ ์ง€์šฐ๊ธฐ (rstrip)

>>> a = " hi "
>>> a.rstrip()
' hi'

 

 

-์–‘์ชฝ ๊ณต๋ฐฑ ์ง€์šฐ๊ธฐ (strip)

>>> a = " hi "
>>> a.strip()
'hi'

 

 

-๋ฌธ์ž์—ด ๋ฐ”๊พธ๊ธฐ (replace)

>>> a = "Life is too short"
>>> a.replace("Life", "Your leg")
'Your leg is too short'

 

 

-๋ฌธ์ž์—ด ๋‚˜๋ˆ„๊ธฐ (split)

>>> a = "Life is too short"
>>> a.split()   ← ๊ณต๋ฐฑ์„ ๊ธฐ์ค€์œผ๋กœ ๋ฌธ์ž์—ด ๋‚˜๋ˆ”
['Life', 'is', 'too', 'short']
>>> b = "a:b:c:d"
>>> b.split(':')   ← : ๊ธฐํ˜ธ๋ฅผ ๊ธฐ์ค€์œผ๋กœ ๋ฌธ์ž์—ด ๋‚˜๋ˆ”
['a', 'b', 'c', 'd']
๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€