logo

Python 문자열 형식() 메서드

그만큼format()>메서드는 개발자가 템플릿 문자열 내의 자리 표시자에 변수와 값을 삽입하여 서식이 지정된 문자열을 만들 수 있는 강력한 도구입니다. 이 방법은 광범위한 응용 프로그램에 대한 텍스트 출력을 구성하는 유연하고 다양한 방법을 제공합니다. 파이썬 문자열 형식() 함수 복잡한 문자열 형식을 보다 효율적으로 처리하기 위해 도입되었습니다. 때때로 우리는 서식 개념을 사용할 때마다 인쇄 문을 작성하는 대신 일반화된 인쇄 문을 만들고 싶을 때가 있습니다.

Python 문자열 형식() 구문

통사론: { }.format(값)



매개변수:

  • 값 : 정수, 부동 소수점 숫자 상수, 문자열, 문자 또는 변수일 수 있습니다.

반환 유형: 자리표시자 위치에 매개변수로 전달된 값을 사용하여 형식화된 문자열을 반환합니다.

Python 예제의 문자열 형식()

Python String format() 메소드의 간단한 데모 파이썬.



파이썬3






name>=> 'Ram'> age>=> 22> message>=> 'My name>is> {>0>}>and> I am {>1>} years> >old. {>1>}>is> my favorite> >number.'.>format>(name, age)> print>(message)>

>

>

산출

My name is Ram and I am 22 years old. 22 is my favorite number.>

.Format() 메소드 사용

내장 문자열 클래스의 이 메서드는 복잡한 변수 대체 및 값 형식 지정을 위한 기능을 제공합니다. 이 새로운 형식 지정 기술은 더욱 우아하다고 간주됩니다. format() 메소드의 일반적인 구문은 string.format(var1, var2,…)입니다. 여기서는 중괄호가 포함된 문자열의 형식을 지정하는 방법을 이해하려고 합니다. 파이썬 .

파이썬3




txt>=> 'I have {an:.2f} Rupees!'> print>(txt.>format>(an>=> 4>))>

>

>

산출

I have 4.00 Rupees!>

단일 포맷터 사용

이 예에서는 문자열 괄호 표기법 str을 시연하는 프로그램. 형식() 메서드. 포맷터는 한 쌍의 중괄호로 정의된 하나 이상의 대체 필드와 자리 표시자를 넣어 작동합니다. { } 문자열로 변환하고 str.format() .

파이썬3




# using format option in a simple string> print>(>'{}, A computer science portal for geeks.'> >.>format>(>'techcodeview.com'>))> # using format option for a> # value stored in a variable> str> => 'This article is written in {}'> print>(>str>.>format>(>'Python'>))> # formatting a string using a numeric constant> print>(>'Hello, I am {} years old !'>.>format>(>18>))>

>

자바 의사코드

>

산출

techcodeview.com, A computer science portal for geeks. This article is written in Python Hello, I am 18 years old!>

여러 자리 표시자가 있는 문자열 형식()

형식을 지정하는 동안 여러 쌍의 중괄호를 사용할 수 있습니다. 파이썬의 문자열 . 문장에 또 다른 변수 대체가 필요하다고 가정해 보겠습니다. 이는 두 번째 중괄호 쌍을 추가하고 두 번째 값을 메서드에 전달하여 수행할 수 있습니다. Python은 자리 표시자를 다음의 값으로 대체합니다. 주문하다.

구문: { } { } .format(값1, 값2)

매개변수: (값1, 값2) : 정수, 부동 소수점 숫자 상수, 문자열, 문자, 심지어 변수일 수도 있습니다. 유일한 차이점은 format() 메서드에서 매개 변수로 전달된 값의 개수가 문자열에 생성된 자리 표시자의 개수와 같아야 한다는 것입니다.

오류 및 예외:

색인오류: string에 추가 자리 표시자가 있고 format() 메서드에 해당 값을 전달하지 않은 경우 발생합니다. Python은 일반적으로 다음과 같은 순서로 기본 인덱스가 있는 자리 표시자를 할당합니다. 0, 1, 2, 3… 매개변수로 전달된 값에 액세스합니다. 따라서 인덱스에 매개변수로 전달된 값이 없는 자리 표시자를 만나면 IndexError가 발생합니다.

str.format() 메서드를 보여주기 위해 여러 자리 표시자를 사용하는 Python 프로그램입니다.

파이썬3




# Multiple placeholders in format() function> my_string>=> '{}, is a {} science portal for {}'> print>(my_string.>format>(>'techcodeview.com'>,>'computer'>,>'geeks'>))> # different datatypes can be used in formatting> print>(>'Hi ! My name is {} and I am {} years old'> >.>format>(>'User'>,>19>))> # The values passed as parameters> # are replaced in order of their entry> print>(>'This is {} {} {} {}'> >.>format>(>'one'>,>'two'>,>'three'>,>'four'>))>

>

>

산출

techcodeview.com, is a computer science portal for geeks Hi! My name is User and I am 19 years old This is one two three four>

문자열 형식() IndexError

자리 표시자의 인덱스 오류 수를 보여주는 Python 프로그램은 4개이지만 전달된 값은 3개뿐입니다.

파이썬3




# parameters in format function.> my_string>=> '{}, is a {} {} science portal for {}'> print>(my_string.>format>(>'techcodeview.com'>,>'computer'>,>'geeks'>))>

>

>

산출

IndexError: tuple index out of range>

이스케이프 시퀀스를 사용하여 문자열 형식 지정

문자열 내에서 특별히 지정된 두 개 이상의 문자를 사용하여 문자열 형식을 지정하거나 명령을 수행할 수 있습니다. 이러한 문자를 이스케이프 시퀀스라고 합니다. 안 Python의 이스케이프 시퀀스 백슬래시()로 시작합니다. 예를 들어, 은 문자 n의 일반적인 의미를 문자 그대로 이스케이프하고 대체 의미(새 줄)를 부여하는 이스케이프 시퀀스입니다.

이스케이프 시퀀스 설명
N 문자열을 새 줄로 나눕니다. print('나는 적절한 시기에 설명하기 위해 이 운율을 디자인했습니다 내가 아는 전부입니다')
가로 탭을 추가합니다. print('시간은 가치 있는 것입니다')
백슬래시를 인쇄합니다. print('진자가 흔들리면서 날아가는 것을 지켜보세요')
' 작은따옴표를 인쇄합니다. print('아무리 노력해도 상관없어요')
큰따옴표를 인쇄합니다. print('정말비현실적이에요')
종소리 같은 소리가 난다 인쇄('a')

위치 및 키워드 인수가 있는 포맷터

자리 표시자 { } 비어 있으면 Python은 str.format()을 통해 전달된 값을 순서대로 대체합니다. str.format() 메서드 내에 존재하는 값은 기본적으로 다음과 같습니다. 튜플 데이터 유형 튜플에 포함된 각 개별 값은 인덱스 번호 0으로 시작하는 인덱스 번호로 호출할 수 있습니다. 이러한 인덱스 번호는 원본 문자열에서 자리 표시자 역할을 하는 중괄호로 전달될 수 있습니다.

구문: {0} {1}.format(위치_인수, 키워드_인수)

매개변수: (위치_인수, 키워드_인수)

  • 위치_인수 정수, 부동 소수점 숫자 상수, 문자열, 문자, 심지어 변수일 수도 있습니다.
  • 키워드_인수 본질적으로 매개변수로 전달되는 일부 값을 저장하는 변수입니다.

예: 위치 키 인수와 함께 포맷터의 사용을 보여줍니다.

파이썬3




# Positional arguments> # are placed in order> print>(>'{0} love {1}!!'>.>format>(>'techcodeview.com'>,> >'Geeks'>))> # Reverse the index numbers with the> # parameters of the placeholders> print>(>'{1} love {0}!!'>.>format>(>'techcodeview.com'>,> >'Geeks'>))> print>(>'Every {} should know the use of {} {} programming and {}'> >.>format>(>'programmer'>,>'Open'>,>'Source'>,> >'Operating Systems'>))> # Use the index numbers of the> # values to change the order that> # they appear in the string> print>(>'Every {3} should know the use of {2} {1} programming and {0}'> >.>format>(>'programmer'>,>'Open'>,>'Source'>,>'Operating Systems'>))> # Keyword arguments are called> # by their keyword name> print>(>'{gfg} is a {0} science portal for {1}'> >.>format>(>'computer'>,>'geeks'>, gfg>=>'techcodeview.com'>))>

>

>

산출

techcodeview.com love Geeks!!  Geeks love techcodeview.com!!  Every programmer should know the use of Open Source programming and Operating Systems  Every Operating Systems should know the use of Source Open programming and programmer  techcodeview.com is a computer science portal for geeks>

Python에서 지정하는 유형

구문의 중괄호 안에 더 많은 매개변수가 포함될 수 있습니다. 형식 코드 구문 사용 {분야 명: 변환} , 어디 분야 명 str.format() 메서드에 대한 인수의 인덱스 번호를 지정하고 변환은 데이터 유형의 변환 코드를 참조합니다.

%s 사용 중 – 형식화하기 전에 str()을 통해 문자열 변환

파이썬3




print>(>'%20s'> %> (>'geeksforgeeks'>, ))> print>(>'%-20s'> %> (>'Interngeeks'>, ))> print>(>'%.5s'> %> (>'Interngeeks'>, ))>

>

>

산출

geeksforgeeks Interngeeks  Inter>

%c 사용 - 성격 포맷하기 전에

파이썬3




type> => 'bug'> result>=> 'troubling'> print>('I wondered why the program was>%>s me. Then> it dawned on me it was a>%>s .'>%> >(result,>type>))>

>

>

산출

I wondered why the program was troubling me. Thenit dawned on me it was a bug .>

%i 사용 부호 있는 십진 정수 및 %디 서식 지정 전 부호 있는 10진수(10진수)

파이썬3




match>=> 12000> site>=> 'Amazon'> print>('>%>s>is> so useful. I tried to look> up mobile>and> they had a nice one that cost>%>d rupees.'>%> (site, match))>

>

>

산출

Amazon is so useful. I tried to lookup mobile and they had a nice one that cost 12000 rupees.>

또 다른 유용한 유형 지정

  • %안에 부호 없는 십진 정수
  • %영형 8진수
  • 에프 – 부동 소수점 디스플레이
  • – 이진수
  • 영형 – 8진수
  • %엑스 – 9 이후 소문자를 포함하는 16진수
  • %엑스 – 9 이후 대문자가 있는 16진수
  • 그것은 – 지수 표기법

지정할 수도 있습니다. 서식 기호 . 유일한 변경 사항은 % 대신 콜론(:)을 사용하는 것입니다.

예를 들어 %s 대신 {:s}를 사용하고 %d 대신 (:d}를 사용합니다.

구문: 문자열 {field_name:conversion} 예제.형식(값)
오류 및 예외:
값오류: 이 메서드에서는 형식 변환 중에 오류가 발생합니다.

10진수 정수를 부동 소수점 숫자 상수로 변환

파이썬3




print>(>'This site is {0:f}% securely {1}!!'>.> >format>(>100>,>'encrypted'>))> # To limit the precision> print>(>'My average of this {0} was {1:.2f}%'> >.>format>(>'semester'>,>78.234876>))> # For no decimal places> print>(>'My average of this {0} was {1:.0f}%'> >.>format>(>'semester'>,>78.234876>))> # Convert an integer to its binary or> # with other different converted bases.> print>(>'The {0} of 100 is {1:b}'> >.>format>(>'binary'>,>100>))> print>(>'The {0} of 100 is {1:o}'> >.>format>(>'octal'>,>100>))>

>

>

산출

This site is 100.000000% securely encrypted!! My average of this semester was 78.23% My average of this semester was 78% The binary of 100 is 1100100 The octal of 100 is 144>

유형 지정 오류

강제 수행 중 ValueError 시연 유형 변환

파이썬3




# When explicitly converted floating-point> # values to decimal with base-10 by 'd'> # type conversion we encounter Value-Error.> print>(>'The temperature today is {0:d} degrees outside !'> >.>format>(>35.567>))> # Instead write this to avoid value-errors> ''' print('The temperature today is {0:.0f} degrees outside !'> >.format(35.567))'''>

>

>

산출

ValueError: Unknown format code 'd' for object of type 'float'>

패딩 대체 또는 공백 생성

문자열이 매개변수로 전달될 때 간격 데모

기본적으로 필드 내에서 문자열은 왼쪽 정렬되고 숫자는 오른쪽 정렬됩니다. 콜론 바로 뒤에 정렬 코드를 배치하여 이를 수정할 수 있습니다.

  <   : left-align text in the field   ^   : center text in the field>: 필드의 텍스트를 오른쪽 정렬>

파이썬3




# To demonstrate spacing when> # strings are passed as parameters> print>(>'{0:4}, is the computer science portal for {1:8}!'> >.>format>(>'techcodeview.com'>,>'geeks'>))> # To demonstrate spacing when numeric> # constants are passed as parameters.> print>(>'It is {0:5} degrees outside !'> >.>format>(>40>))> # To demonstrate both string and numeric> # constants passed as parameters> print>(>'{0:4} was founded in {1:16}!'> >.>format>(>'techcodeview.com'>,>2009>))> # To demonstrate aligning of spaces> print>(>'{0:^16} was founded in {1:<4}!'> >.>format>(>'techcodeview.com'>,>2009>))> print>(>'{:*^20s}'>.>format>(>'Geeks'>))>

>

>

출력 :

techcodeview.com, is the computer science portal for geeks ! It is 40 degrees outside! techcodeview.com was founded in 2009!  techcodeview.com was founded in 2009 ! *******Geeks********>

응용

포맷터는 일반적으로 데이터를 구성하는 데 사용됩니다. 포맷터는 시각적인 방법으로 많은 데이터를 구성하는 데 사용될 때 가장 잘 보입니다. 사용자에게 데이터베이스를 표시하는 경우 포맷터를 사용하여 필드 크기를 늘리고 정렬을 수정하면 출력을 더 읽기 쉽게 만들 수 있습니다.

예: format()을 사용하여 대용량 데이터의 구성을 보여주기 위해

파이썬3




# which prints out i, i ^ 2, i ^ 3,> # i ^ 4 in the given range> # Function prints out values> # in an unorganized manner> def> unorganized(a, b):> >for> i>in> range>(a, b):> >print>(i, i>*>*>2>, i>*>*>3>, i>*>*>4>)> # Function prints the organized set of values> def> organized(a, b):> >for> i>in> range>(a, b):> ># Using formatters to give 6> ># spaces to each set of values> >print>(>'{:6d} {:6d} {:6d} {:6d}'> >.>format>(i, i>*>*> 2>, i>*>*> 3>, i>*>*> 4>))> # Driver Code> n1>=> int>(>input>(>'Enter lower range :- '>))> n2>=> int>(>input>(>'Enter upper range :- '>))> print>(>'------Before Using Formatters-------'>)> # Calling function without formatters> unorganized(n1, n2)> print>()> print>(>'-------After Using Formatters---------'>)> print>()> # Calling function that contains> # formatters to organize the data> organized(n1, n2)>

>

str을 int로 변환하는 방법
>

출력 :

Enter lower range :- 3 Enter upper range :- 10 ------Before Using Formatters------- 3 9 27 81 4 16 64 256 5 25 125 625 6 36 216 1296 7 49 343 2401 8 64 512 4096 9 81 729 6561 -------After Using Formatters---------  3 9 27 81  4 16 64 256  5 25 125 625  6 36 216 1296  7 49 343 2401  8 64 512 4096  9 81 729 6561>

문자열 형식화를 위해 사전 사용

사전을 사용하여 형식을 지정해야 하는 문자열의 자리 표시자에 값을 압축 해제합니다. 우리는 기본적으로 ** 값을 압축 해제합니다. 이 방법은 SQL 쿼리를 준비하는 동안 문자열 대체에 유용할 수 있습니다.

파이썬3




introduction>=> 'My name is {first_name} {middle_name} {last_name} AKA the {aka}.'> full_name>=> {> >'first_name'>:>'Tony'>,> >'middle_name'>:>'Howard'>,> >'last_name'>:>'Stark'>,> >'aka'>:>'Iron Man'>,> }> # Notice the use of '**' operator to unpack the values.> print>(introduction.>format>(>*>*>full_name))>

>

>

산출:

My name is Tony Howard Stark AKA the Iron Man.>

목록이 있는 Python 형식()

부동 소수점 값 목록이 주어지면 작업은 모든 부동 소수점 값을 소수점 2자리로 자르는 것입니다. 작업을 수행하는 다양한 방법을 살펴보겠습니다.

파이썬3




# Python code to truncate float> # values to 2 decimal digits.> > # List initialization> Input> => [>100.7689454>,>17.232999>,>60.98867>,>300.83748789>]> > # Using format> Output>=> [>'{:.2f}'>.>format>(elem)>for> elem>in> Input>]> > # Print output> print>(Output)>

>

>

산출

['100.77', '17.23', '60.99', '300.84']>