Language/Python

[Python/ํŒŒ์ด์ฌ] ๋ฌธ์ž์—ด(String) ์ž๋ฃŒํ˜• ์ •๋ฆฌ - ๋ฌธ์ž ๊ฐœ์ˆ˜ ์„ธ๊ธฐ, ํŠน์ • ๋ฌธ์ž ์œ„์น˜, ๊ณต๋ฐฑ ์ง€์šฐ๊ธฐ ๋“ฑ

meeeeejin 2021. 3. 5. 10:08

1. ๋ฌธ์ž์—ด ์ดˆ๊ธฐํ™”(์„ ์–ธ)

  • ํฐ๋”ฐ์˜ดํ‘œ ์ด์šฉ
    s = "Hello World" ๋˜๋Š” s = """Hello World"""
  • ์ž‘์€๋”ฐ์˜ดํ‘œ ์ด์šฉ
    s = 'Hello World' ๋˜๋Š” s = '''Hello World'''
  • ๋ฌธ์ž์—ด ์•ˆ์— ์ž‘์€๋”ฐ์˜ดํ‘œ(') ๋˜๋Š” ํฐ๋”ฐ์˜ดํ‘œ(") ๋ฅผ ํฌํ•จํ•  ๋•Œ๋Š” ๋‹ค๋ฅธ ๋”ฐ์˜ดํ‘œ๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ๋จ
    s = "I'm a student"     #๋ฌธ์ž์—ด ๋‚ด์˜ '๋Š” ๋ฌธ์ž๋กœ ์ธ์‹๋จ
  • ๋˜๋Š” ๋ฐฑ์Šฌ๋ž˜์‹œ(\)๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๋ฐฉ๋ฒ•๋„ ์žˆ์Œ(์ด์Šค์ผ€์ดํ”„ ์ฝ”๋“œ)
    s = "I\'m a student"

 

 

2. ๋ฌธ์ž์—ด ์—ฐ์‚ฐ

  • ๋ฌธ์ž์—ด ๋”ํ•ด์„œ ์—ฐ๊ฒฐํ•˜๊ธฐ(Concatenation)
    - a = "Hello", b = " World" ์ผ ๊ฒฝ์šฐ
    - a + b ๋Š” "Hello World"๋ฅผ ๋ฐ˜ํ™˜
  • ๋ฌธ์ž์—ด ๊ณฑํ•˜๊ธฐ
    - a = "Hello"์ผ ๊ฒฝ์šฐ
    - a * 2 ๋Š” "HelloHello"๋ฅผ ๋ฐ˜ํ™˜
  • ๋ฌธ์ž์—ด ๊ธธ์ด
    - len ํ•จ์ˆ˜๋ฅผ ์ด์šฉํ•ด์„œ ๋ฌธ์ž์—ด์˜ ๊ธธ์ด ๊ตฌํ•จ
    - a = "Hello"์ผ ๊ฒฝ์šฐ len(a)๋Š” 5๋ฅผ ๋ฐ˜ํ™˜

 

 

3. ๋ฌธ์ž์—ด ์ธ๋ฑ์‹ฑ(Indexing)๊ณผ ์Šฌ๋ผ์ด์‹ฑ(Slicing)

 

 

4. ๋ฌธ์ž์—ด ๊ด€๋ จ ๋ฉ”์„œ๋“œ(Method)

  • ๋ฌธ์ž ๊ฐœ์ˆ˜ ์„ธ๊ธฐ(count)
    - a.count('x')
    - ๋ฌธ์ž์—ด ์ค‘ ๋ฌธ์ž x์˜ ๊ฐœ์ˆ˜๋ฅผ ๋ฐ˜ํ™˜
  • ํŠน์ • ๋ฌธ์ž์˜ ์œ„์น˜(find)
    - a.find('x')
    - ๋ฌธ์ž์—ด ์ค‘ ๋ฌธ์ž x๊ฐ€ ์ฒ˜์Œ์œผ๋กœ ๋‚˜์˜จ ์œ„์น˜ ๋ฐ˜ํ™˜
    - ๋งŒ์•ฝ ์ฐพ๋Š” ๋ฌธ์ž๋‚˜ ๋ฌธ์ž์—ด์ด ์กด์žฌํ•˜์ง€ ์•Š์œผ๋ฉด -1 ๋ฐ˜ํ™˜
  • ํŠน์ • ๋ฌธ์ž์˜ ์œ„์น˜(index)
    - a.index('x')
    - ๋ฌธ์ž์—ด ์ค‘ ๋ฌธ์ž x๊ฐ€ ์ฒ˜์Œ์œผ๋กœ ๋‚˜์˜จ ์œ„์น˜ ๋ฐ˜ํ™˜
    - ๋งŒ์•ฝ ์ฐพ๋Š” ๋ฌธ์ž๋‚˜ ๋ฌธ์ž์—ด์ด ์กด์žฌํ•˜์ง€ ์•Š์œผ๋ฉด ์˜ค๋ฅ˜ ๋ฐœ์ƒ(find์™€ ๋‹ค๋ฆ„)
  • ๋ฌธ์ž์—ด ์‚ฝ์ž…(join)
    - ",".join('abcd')            # 'a, b, c, d'
    - ๋ฌธ์ž์—ด 'abcd'์˜ ๊ฐ๊ฐ์˜ ๋ฌธ์ž ์‚ฌ์ด์— ','๋ฅผ ์‚ฝ์ž…
  • ๊ณต๋ฐฑ ์ง€์šฐ๊ธฐ(strip)
    - a.strip()
    - ๋ฌธ์ž์—ด ์–‘์ชฝ์— ์žˆ๋Š” ํ•œ ์นธ ์ด์ƒ์˜ ์—ฐ์†๋œ ๊ณต๋ฐฑ์„ ๋ชจ๋‘ ์ง€์›€
    - ์™ผ์ชฝ ๊ณต๋ฐฑ๋งŒ ์ง€์šฐ๊ธฐ( a.lstrip() ), ์˜ค๋ฅธ์ชฝ ๊ณต๋ฐฑ๋งŒ ์ง€์šฐ๊ธฐ( a.rstrip() )
  • ๋ฌธ์ž์—ด ๋ฐ”๊พธ๊ธฐ(replace)
    - a.replace(๋ฐ”๊พธ๊ณ  ์‹ถ์€ ๋ฌธ์ž์—ด, ๋ฌด์—‡์œผ๋กœ ๋ฐ”๊ฟ€ ๊ฒƒ์ธ์ง€)
    - a.replace("Hello", "Good Bye")
    - ๋ฌธ์ž์—ด a ๋‚ด์˜ "Hello"๊ฐ€ "Good Bye"๋กœ ๋ฐ”๋€œ
  • ๋ฌธ์ž์—ด ๋‚˜๋ˆ„๊ธฐ(split)
    - a.spilt()
    - ๊ณต๋ฐฑ(์ŠคํŽ˜์ด์Šค, ํƒญ, ์—”ํ„ฐ ๋“ฑ)์„ ๊ธฐ์ค€์œผ๋กœ ๋ฌธ์ž์—ด์„ ๋‚˜๋ˆ ์คŒ
    - a.split(',') ์ฒ˜๋Ÿผ ํŠน์ • ๊ฐ’์„ ๋„ฃ์–ด์ฃผ๋ฉด ๊ทธ ๊ฐ’์„ ๊ธฐ์ค€์œผ๋กœ ๋ฌธ์ž์—ด์„ ๋‚˜๋ˆ ์คŒ
    - ์˜ˆ์‹œ) a = "a,b,c,d,e"์ผ ๊ฒฝ์šฐ a.spilt(',') ์€ ['a', 'b', 'c', 'd', 'e'] ๋ฐ˜ํ™˜

 

 

 

์ฐธ๊ณ : wikidocs.net/13

728x90