udem.py - (7) Strings Properties & Methods & Formatting

Gomi_kery·2022년 9월 8일
0

udem.py

목록 보기
8/28
post-thumbnail

문자열의 불변성

  • 인덱싱으로 문자열의 개별적 요소를 변경할 수 없음.

order = "2nd"

value를 "3nd"로 바꾸고 싶을 때,
order[0] = "3" 과 같이 문자열의 글자 or 요소 만 갖고와서 변경하는 것은 불가능

order[1::]        # order의 2번째 이후 글자를 받아옴
> "nd"
"3" + order[1::]  # "3" 이라는 텍스트와 받아온 "nd"를 이어 붙임
> 3nd

order = "3" + order[1::] 
# order의 value를 재할당하는 방식으로는 바꿀 수 있음.

Method (일부)

upper

: 모든 글자를 대문자로 변경

x = "Hello World"

x.upper()
> "HELLO WORLD"

lower

: 모든 글자를 소문자로 변경

x = "Hello World"

x.lower()
> "hello world"

split

: 공백이나 구분자를 기준으로 문자열을 리스트로 변경

x = "Hello World"

x.split()
> ["Hello", "World"]

Formatting

문자열 보간 (Interpolation) : 문자열에 문자열을 붙여넣는 방법.

.format()

  • 문자열을 인덱스 위치에 따라 삽입 가능.
  • 여러가지 단어를 .format() 안에 입력한 순서대로 넣을 수 있음.
  • {} 안에 인덱스 숫자를 입력하여 .format() 의 텍스트 순서를 변경하지 않아도
    순서를 변경할 수 있음.
  • format()에서 문자열에 Keyword를 할당한 뒤 호출할 수 있음.
# .format("문자열") → {} 에 삽입
print("문자열 { }" .format("문자열"))
print("World of {}".format("Warcraft"))               
> World of Warcraft

print("{} of {} {}".format("Storm","the","heros"))    
> Storm of the Heros

print("{2} of {1} {0}".format("Strom","the","Heros")) 
> Heros of the Strom

print("{name} is {comm} Game".format(comm="Blizzard",name="World of Warcraft"))
> 'World of Warcraft' is Blizzard Game"
#  Float formatting "{value:width.precision f}"
pie = 355/113 

print("pie is {p}".format(p=pie))
> pie is 3.1415929203539825

print("pie is {p:5.4f}".format(p=pie))
> pie is 3.1416

f-string

  • formatted string literals
  • 문자열 안에 직접 변수이름 or 결과를 작성하는 방법.
age = 38

# formatying
print("my age is {}".format(age))
> my age is 38

# f-string
print(f"my age is {age}")
> my age is 38
game = "World of Warcraft"
comm = "Blizzard"

print(f"{game} is {comm} games")
profile
QA. 손으로 할 수 있는 모든 것을 좋아합니다.

0개의 댓글