반응형
문자열 형식 지정 시 동일한 값을 여러 번 삽입
이 양식의 줄이 있습니다.
s='arbit'
string='%s hello world %s hello world %s' %(s,s,s)
문자열의 모든 %s 값(예: s)이 동일합니다.이 글을 쓰는 더 좋은 방법이 있을까요? (3번씩 열거하는 것보다)
Python 2.6 및 Python 3.x에서 사용할 수 있는 고급 문자열 형식을 사용할 수 있습니다.
incoming = 'arbit'
result = '{0} hello world {0} hello world {0}'.format(incoming)
incoming = 'arbit'
result = '%(s)s hello world %(s)s hello world %(s)s' % {'s': incoming}
문자열 형식 지정 작업에 대한 이해를 얻기 위해 이 항목을 읽어보는 것이 좋습니다.
사전 형식 형식을 사용할 수 있습니다.
s='arbit'
string='%(key)s hello world %(key)s hello world %(key)s' % {'key': s,}
더 나은 의미가 무엇인지에 따라 다릅니다.중복 제거가 목표인 경우 이 기능이 작동합니다.
s='foo'
string='%s bar baz %s bar baz %s bar baz' % (3*(s,))
프스트링스
사용 중인 경우Python 3.6+당신은 소위 새로운 것을 사용할 수 있습니다.f-strings형식화된 문자열을 나타내며 문자를 추가하여 사용할 수 있습니다.f이를 f-string으로 식별하기 위한 문자열의 시작 부분.
price = 123
name = "Jerry"
print(f"{name}!!, {price} is much, isn't {price} a lot? {name}!")
>Jerry!!, 123 is much, isn't 123 a lot? Jerry!
f-string 사용의 주요 이점은 읽기 쉽고, 속도가 빠르며, 성능이 향상된다는 것입니다.
모두를 위한 판다 소스:Daniel Y. Chen의 Python 데이터 분석
벤치마크
의심할 여지 없이 새로운 것.f-strings문자열을 다시 매핑할 필요가 없기 때문에 더 읽기 쉽지만, 위의 인용문에 명시된 것처럼 더 빠른가요?
price = 123
name = "Jerry"
def new():
x = f"{name}!!, {price} is much, isn't {price} a lot? {name}!"
def old():
x = "{1}!!, {0} is much, isn't {0} a lot? {1}!".format(price, name)
import timeit
print(timeit.timeit('new()', setup='from __main__ import new', number=10**7))
print(timeit.timeit('old()', setup='from __main__ import old', number=10**7))
> 3.8741058271543776 #new
> 5.861819514350163 #old
천만 번의 테스트를 실행해보니, 새로운 것이f-strings매핑 속도가 더 빠릅니다.
>>> s1 ='arbit'
>>> s2 = 'hello world '.join( [s]*3 )
>>> print s2
arbit hello world arbit hello world arbit
언급URL : https://stackoverflow.com/questions/1225637/inserting-the-same-value-multiple-times-when-formatting-a-string
반응형
'programing' 카테고리의 다른 글
| Oracle SQL Developer 3.1.07 listagg를 사용한 문자 사이의 추가 공백 (0) | 2023.07.22 |
|---|---|
| JSON 개체를 통해 반복 (0) | 2023.07.22 |
| Linux에서는 strrev() 기능을 사용할 수 없습니까? (0) | 2023.07.22 |
| '따옴표가 붙은 문자열이 제대로 종료되지 않음'을(를) 유발하는 SQL에서 단일 따옴표를 이스케이프하는 방법은 무엇입니까? (0) | 2023.07.22 |
| python BeautifulSoup 구문 분석 테이블 (0) | 2023.07.22 |