๐Ÿ–ฅ๏ธ[Python] 2. ๋ฌธ์ž ๋ฐ์ดํ„ฐ

thisk336ยท2023๋…„ 5์›” 11์ผ
0

Python

๋ชฉ๋ก ๋ณด๊ธฐ
2/17
post-thumbnail

๋ฌธ์ž์—ด(String)

  • ๋ฌธ์ž์—ด ๋ฐ์ดํ„ฐ๋ž€, ๋ฌธ์ž(character)์˜ ๋‚˜์—ด์„ ์˜๋ฏธํ•œ๋‹ค. e.g. "Hello world"

string ; Character Sequence

  • ํŒŒ์ด์ฌ์— ๋‹ค๋ฃฐ ์ˆ˜ ์žˆ๋Š” ๋ฌธ์ž์—ด์˜ ํฌ๊ธฐ๋„ ์ œํ•œ์ด ์—†๋‹ค.

  • ํŒŒ์ด์ฌ์—์„  '์™€ " ๋‘ ๊ฐ€์ง€์˜ ๊ธฐํ˜ธ๋ฅผ ํ†ตํ•ด ๋ฌธ์ž์—ด์„ ๋‚˜ํƒ€๋‚ธ๋‹ค. ์ฆ‰ ' ๋ถ€ํ„ฐ ' ๊นŒ์ง€ ๋˜๋Š” " ๋ถ€ํ„ฐ " ๊นŒ์ง€ ํ•˜๋‚˜์˜ ๋ฌธ์ž์—ด์ด๋‹ค. e.g. 'Hello', "World"

  • ์ปดํ“จํ„ฐ๋Š” ๋ฌธ์ž(character)๋ฅผ encodingํ•˜์—ฌ ์ˆซ์ž๋กœ ํ‘œํ˜„ํ•œ๋‹ค. ์•Œ๋ ค์ง„ ์˜ˆ๋กœ ASCII, utf-8, cp949๊ฐ€ ์žˆ๋‹ค.

์ปดํ“จํ„ฐ๋Š” ๋ฌธ์ž๋ฅผ ์ˆซ์ž๋กœ ์ธ์‹ํ•œ๋‹ค. e.g. ASCII ์ฝ”๋“œ๋กœ ๋ณ€ํ™˜ํ•˜๋ฉด A->65, a->97

  • ํ˜„์žฌ ์ „์„ธ๊ณ„์ ์œผ๋กœ ์›น์—์„œ ์‚ฌ์šฉ๋˜๋Š” ๊ตญ์ œ ํ‘œ์ค€์€ UTF-8(Universal code character set Transformation Format - 8-bit)์ด๋‹ค.

๋ฌธ์ž์—ด์„ ๋งŒ๋“œ๋Š” ์—ฌ๋Ÿฌ๊ฐ€์ง€ ๋ฐฉ๋ฒ•

s1 = 'Hello'
s2 = "World!"
s3 ="""To Be Great is # """์„ ์‚ฌ์šฉํ•˜๊ฒŒ ๋˜๋ฉด enter๋ฅผ ํฌํ•จํ•ด์„œ ์ถœ๋ ฅํ•œ๋‹ค.
To Be Misunderstood.
- Ralph Waldo Emerson
"""
s4 = "i'm a boy." # python์—์„œ ""๊ณผ ''์„ ๋‘˜ ๋‹ค ์‚ฌ์šฉํ•˜๋Š” ์ด์œ 

ํŠน์ˆ˜ ๋ฌธ์ž ํ‘œํ˜„ (escape code)

# \n -> new line
print("Hello\nWorld")
# \t -> tab
print("Hello\tWorld")

๋ฌธ์ž์—ด ์—ฐ์‚ฐํ•˜๊ธฐ

s = "Hello" 
s1 = "World"
s + ' ' + s1
s2 = "-"
s2 * 20
s3 = "Enjoy your life."
len(s3) # ๋ฌธ์ž์—ด์˜ ๊ธธ์ด๋ฅผ ์ถœ๋ ฅํ•˜๋Š” ํ•จ์ˆ˜ 

๋ฌธ์ž์—ด Formatting

  • ๋ฌธ์ž์—ด์„ ์ถœ๋ ฅํ•  ๋•Œ(print ํ•จ์ˆ˜๋ฅผ ์ด์šฉํ•˜์—ฌ) ํŠน์ • format์„ ์ง€์ •ํ•˜๊ณ  ์‹ถ์€ ๊ฒฝ์šฐ์—๋Š” ์–ด๋–ป๊ฒŒ ํ•ด์•ผํ• ๊นŒ?

e.g. OOO๋‹˜์˜ ์ฃผ๋ฏผ๋“ฑ๋ก๋ฒˆํ˜ธ๋Š” XXXXXXX-XXXXXXX์ž…๋‹ˆ๋‹ค.

  • ๋ฌธ์ž์—ด ํฌ๋งท์—๋Š” ํฌ๊ฒŒ 3๊ฐ€์ง€๊ฐ€ ์žˆ๋‹ค. (๊ธฐํ˜ธ์— ๋งž๊ฒŒ ์‚ฌ์šฉํ•˜๋ฉด ๋ฉ๋‹ˆ๋‹ค)

"์‚ฌ๊ณผ๋Š” 4๊ฐœ์žˆ๋‹ค."

1) print format ์‚ฌ์šฉ

print("%s๋Š” %d๊ฐœ ์žˆ๋‹ค." % ("์‚ฌ๊ณผ", 4))

2) str.format ํ•จ์ˆ˜ ์‚ฌ์šฉ

print("{}๋Š” {}๊ฐœ ์žˆ๋‹ค.".format("์‚ฌ๊ณผ", 4))

3) f-string ์‚ฌ์šฉ

apple = "์‚ฌ๊ณผ", count = 4

print(f"{apple}๋Š” {count}๊ฐœ ์žˆ๋‹ค.")

apple = "์‚ฌ๊ณผ"
count = 4
print("%s๋Š” %d๊ฐœ ์žˆ๋‹ค." % ("์‚ฌ๊ณผ", 4))
print("{}๋Š” {}๊ฐœ ์žˆ๋‹ค.".format("์‚ฌ๊ณผ",4))
print(f"{apple}๋Š” {count}๊ฐœ ์žˆ๋‹ค.")

๋ฌธ์ž์—ด ๊ด€๋ จ ํ•จ์ˆ˜๋“ค

1) (์˜์–ด) ๋Œ€์†Œ๋ฌธ์ž ๋ฐ”๊พธ๊ธฐ

s = "Hello Python"
print(s.upper()) # ๋ชจ๋“  ๋ฌธ์ž๋ฅผ ๋Œ€๋ฌธ์ž๋กœ ๋ฐ”๊พผ๋‹ค.
print(s.lower()) # ๋ชจ๋“  ๋ฌธ์ž๋ฅผ ์†Œ๋ฌธ์ž๋กœ ๋ฐ”๊พผ๋‹ค.

2) ๋ฌธ์ž ๊ณต๋ฐฑ ์ง€์šฐ๊ธฐ

s = "         ๋‚˜๋Š” ์˜ค๋Š˜ ์ ์‹ฌ์„ ๋จน์—ˆ์Šต๋‹ˆ๋‹ค.         "
s.strip() # ๋ฌธ์ž์—ด ์•ˆ์— ์žˆ๋Š” ๋ชจ๋“  ๊ณต๋ฐฑ์„ ์ง€์šด๋‹ค.

3) ๋ฌธ์ž์—ด ์‚ฝ์ž…

s = ('010', '1234', '3456')
'-'.join(s) # ๋ฌธ์ž์—ด ์ค‘๊ฐ„์— '-'๋ฅผ ์‚ฝ์ž…ํ•œ๋‹ค.

4) ๋ฌธ์ž์—ด ๋‚˜๋ˆ„๊ธฐ

s = "Life is too short."
s.split() # ๋„์–ด์“ฐ๊ธฐ ๊ธฐ์ค€์œผ๋กœ ๋ฌธ์ž๋ฅผ ๋‚˜๋ˆˆ๋‹ค.

5) ๋ฌธ์ž์—ด ๋ฐ”๊พธ๊ธฐ

s = "Life is too Short."
print(s.replace("Life","This pencil")) # "Life"๋ฅผ "This pencil"๋กœ ๋ฐ”๊พผ๋‹ค.

0๊ฐœ์˜ ๋Œ“๊ธ€