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

Programming Language/Python

Python - strip ํ•จ์ˆ˜์™€ split ํ•จ์ˆ˜์˜ ์ฐจ์ด ๋ฐ ์‚ฌ์šฉ๋ฐฉ๋ฒ•

728x90
๋ฐ˜์‘ํ˜•

๐ŸŸก Python์˜ strip ํ•จ์ˆ˜ VS split ํ•จ์ˆ˜

 

โœ… strip ํ•จ์ˆ˜

: ํŒŒ์ด์ฌ ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ์—์„œ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋Š” ๋‚ด์žฅ ํ•จ์ˆ˜์˜ ์ผ๋ถ€๋กœ์จ, ์›๋ž˜ ๋ฌธ์ž์—ด์˜ ์‹œ์ž‘๊ณผ ๋์—์„œ ์ฃผ์–ด์ง„ ๋ฌธ์ž๋ฅผ ์ œ๊ฑฐํ•œ๋‹ค. ๊ธฐ๋ณธ์ ์œผ๋กœ strip() ํ•จ์ˆ˜๋Š” ๋ฌธ์ž์—ด์˜ ์‹œ์ž‘๊ณผ ๋์—์„œ ๊ณต๋ฐฑ์„ ์ œ๊ฑฐํ•œ ํ›„ ๋ฐ˜ํ™˜ํ•œ๋‹ค. ๋งŒ์•ฝ, ๊ด„ํ˜ธ ์•ˆ์— ํŠน์ • ๊ฐ’์„ ๋„ฃ์„ ๊ฒฝ์šฐ์—๋Š” ํ•ด๋‹นํ•˜๋Š” ๋ฌธ์ž์—ด์„ ์ œ๊ฑฐํ•  ์ˆ˜ ์žˆ๋‹ค.

strip ํ•จ์ˆ˜์—๋Š” rstrip, lstrip, strip์œผ๋กœ ์ด 3๊ฐ€์ง€๊ฐ€ ์žˆ๋‹ค. rstrip์€ ์˜ค๋ฅธ์ชฝ์— ์žˆ๋Š” ๊ฒƒ๋งŒ(๊ณต๋ฐฑ or ํŠน์ • ๋ฌธ์ž) ์ œ๊ฑฐํ•˜๊ณ , lstrip์€ ์™ผ์ชฝ์— ์žˆ๋Š” ๊ฒƒ๋งŒ ์ œ๊ฑฐํ•˜๊ณ , strip์€ ์–‘์ชฝ ๋‹ค ์ œ๊ฑฐํ•œ๋‹ค.

 

โžก๏ธ strip()

# ๊ณต๋ฐฑ์„ ์ œ๊ฑฐํ•˜๋Š” ๊ฒฝ์šฐ
string = "     abcde     "
string.strip()

>>> 'abcde'


# ํŠน์ • ๋ฌธ์ž์—ด์„ ์ œ๊ฑฐํ•˜๋Š” ๊ฒฝ์šฐ
string = "     abcde     "
string.strip('c')

>>> 'abde'

 

โžก๏ธ lstrip()

# ๊ณต๋ฐฑ์„ ์ œ๊ฑฐํ•˜๋Š” ๊ฒฝ์šฐ
string = "     abcde     "
string.lstrip()

>>> 'abcde     '


# ํŠน์ • ๋ฌธ์ž์—ด์„ ์ œ๊ฑฐํ•˜๋Š” ๊ฒฝ์šฐ
string = "     oooabcdeooo     "
string.lstrip('o')

>>> 'abcdeooo'

 

โžก๏ธ rstrip()

# ๊ณต๋ฐฑ์„ ์ œ๊ฑฐํ•˜๋Š” ๊ฒฝ์šฐ
string = "     abcde     "
string.rstrip()

>>> '     abcde'


# ํŠน์ • ๋ฌธ์ž์—ด์„ ์ œ๊ฑฐํ•˜๋Š” ๊ฒฝ์šฐ
string = "     oooabcdeooo     "
string.rstrip('o')

>>> 'oooabcde'

 

 

 

โœ… split ํ•จ์ˆ˜

: ๋ฌธ์ž์—ด์„ ์˜ˆ์˜๊ฒŒ ๋‚˜๋ˆ ์„œ ๋ฆฌ์ŠคํŠธ๋กœ ๋งŒ๋“ค ๋•Œ ๊ฐ€์žฅ ๋งŽ์ด ์‚ฌ์šฉํ•˜๋Š” ํ•จ์ˆ˜์ด๋‹ค. split() ๊ด„ํ˜ธ ์•ˆ์— ์•„๋ฌด๊ฒƒ๋„ ๋„ฃ์ง€ ์•Š์œผ๋ฉด ๊ณต๋ฐฑ(๋„์–ด์“ฐ๊ธฐ, ํƒญ ๋“ฑ)์„ ๊ธฐ์ค€์œผ๋กœ ๋ฌธ์ž์—ด์„ ๋‚˜๋ˆ„๊ณ , ๋งŒ์•ฝ ํŠน์ • ๋ฌธ์ž๊ฐ€ ๋“ค์–ด๊ฐ€ ์žˆ๋‹ค๋ฉด ํ•ด๋‹น ๋ฌธ์ž๋ฅผ ๊ธฐ์ค€์œผ๋กœ ๋‚˜๋ˆˆ๋‹ค. ๋‚˜๋ˆ„์–ด์ง„ ๊ฐ’์€ ๋ฆฌ์ŠคํŠธ์˜ ์š”์†Œ๋กœ ์ €์žฅ๋œ๋‹ค.

 

โžก๏ธ split()

string = "I am so pretty"

a = string.split()


>>> ['I', 'am', 'so', 'pretty']

 

 

 

โš ๏ธ ์ฃผ์˜ ํ•ด์•ผ ํ•  ์ 

Python์—์„œ ์—”ํ„ฐ๋Š” '\n'์œผ๋กœ ์ธ์‹ํ•œ๋‹ค. ๋”ฐ๋ผ์„œ for๋ฌธ์„ ์‚ฌ์šฉํ•  ๋•Œ ์ž…๋ ฅ๋˜๋Š” ๋ฌธ์ž์—ด๋“ค์ด ์ž๋™์ ์œผ๋กœ ์ค„๋ฐ”๊ฟˆ์ด ๋œ๋‹ค๋ฉด, ์ด ๋•Œ๋Š” strip ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ๊ณต๋ฐฑ์„ ์ œ๊ฑฐํ•ด์ฃผ์–ด์•ผ ํ•œ๋‹ค. ๊ทธ๋ ‡์ง€ ์•Š์œผ๋ฉด ์ •ํ•ด์ง„ ๋ฆฌ์ŠคํŠธ ์ธ๋ฑ์Šค ๋ฒ”์œ„๋ฅผ ๋ฒ—์–ด๋‚˜๊ฒŒ ๋ผ์„œ error ๊ฐ€ ๋‚œ๋‹ค. ์ฝ”๋“œ๋ฅผ ์งค ๋•Œ๋Š” ๋ฐ˜๋“œ์‹œ ์ด ์ ์„ ํ™•์ธํ•  ๊ฒƒ!

ex)

# strip
graph = [list(sys.stdin.readline().strip()) for _ in range(R)]

# split
graph = [list(sys.stdin.readline().split()) for _ in range(R)]

 

 

 

 

728x90
๋ฐ˜์‘ํ˜•