Programing

파이썬에서 "문자열"과 "문자열"사이에 차이가 있습니까?

lottogame 2020. 12. 3. 07:23
반응형

파이썬에서 "문자열"과 "문자열"사이에 차이가 있습니까?


이 질문에 이미 답변이 있습니다.

PHP에서 "큰 따옴표"로 묶인 문자열은 대체 할 변수에 대해 구문 분석되지만 '작은 따옴표'로 묶인 문자열은 그렇지 않습니다. 파이썬에서도 이것이 적용됩니까?


아니오 :

2.4.1. 문자열 및 바이트 리터럴

... 일반 영어 : 두 가지 유형의 리터럴은 모두 일치하는 작은 따옴표 ( ') 또는 큰 따옴표 ( ")로 묶을 수 있습니다 . 또한 세 개의 작은 따옴표 또는 큰 따옴표의 일치하는 그룹으로 묶을 수 있습니다 (일반적으로 세 개의 따옴표로 묶인 문자열이라고 함). 백 슬래시 ( \) 문자는 개행 문자, 백 슬래시 자체 또는 따옴표 문자와 같이 특별한 의미가있는 문자를 이스케이프하는 데 사용됩니다.


Python은 '와 "가 동일한 기능을 갖는 몇 안되는 (?) 언어 중 하나입니다. 일반적으로 선택은 내부 내용에 따라 다릅니다. 작은 따옴표가있는 문자열을 인용하려면 큰 따옴표를 사용합니다. 문자열에서 문자를 이스케이프해야하는 것을 줄이기 위해 반대의 경우도 마찬가지입니다.

예 :

"this doesn't require escaping the single quote"
'she said "quoting is easy in python"'

이것은 파이썬 문서의 "문자열 리터럴"페이지에 설명되어 있습니다 :


일부 다른 언어에서는 작은 따옴표를 사용하면 메타 문자가 해석되지 않습니다. Ruby에서이 예를 살펴보세요

irb(main):001:0> puts "string1\nstring2"
string1
string2
=> nil
irb(main):002:0> puts 'string1\nstring2'
string1\nstring2
=> nil

Python에서 문자열을 문자 그대로 가져 오려면 원시 문자열 ( 'r'문자가 앞에 오는 문자열)을 사용할 수 있습니다.

>>> print 'string1\nstring2'
string1
string2
>>> print r'string1\nstring2'
string1\nstring2

파이썬에서 작은 따옴표와 큰 따옴표로 묶인 문자열은 동일합니다. 유일한 차이점은 작은 따옴표로 묶인 문자열에는 이스케이프 처리되지 않은 큰 따옴표 문자가 포함될 수 있으며 그 반대의 경우도 마찬가지입니다. 예를 들면 :

'a "quoted" word'
"another 'quoted' word"

그런 다음 다시 인용 부호와 개행 문자를 모두 이스케이프 해제 할 수있는 삼중 인용 문자열이 있습니다.

명명 된 지정자와 locals () 내장을 사용하여 문자열의 변수를 대체 할 수 있습니다.

name = 'John'
lastname = 'Smith'
print 'My name is %(name)s %(lastname)s' % locals()  # prints 'My name is John Smith'

대화 형 Python 인터프리터는 작은 따옴표를 선호합니다.

>>> "text"
'text'

>>> 'text'
'text'

이것은 초보자에게 혼란 스러울 수 있으므로 작은 따옴표를 사용합니다 (다른 코딩 표준이없는 경우).


"와 '문자열 인용의 차이점은 스타일에 불과합니다. 단 하나는 문자열 내용 내에서 다른 하나를 이스케이프 할 필요가 없다는 점입니다.

스타일

PEP8 은 일관된 규칙을 권장하고 PEP257독 스트링 이 삼중 큰 따옴표를 사용하도록 제안합니다.

Python에서 작은 따옴표로 묶인 문자열과 큰 따옴표로 묶은 문자열은 동일합니다. 이 PEP는이를 권장하지 않습니다. 규칙을 선택하고 준수하십시오. 그러나 문자열에 작은 따옴표 또는 큰 따옴표 문자가 포함 된 경우 다른 하나를 사용하여 문자열에서 백 슬래시를 방지하십시오. 가독성을 향상시킵니다.

삼중 따옴표로 묶인 문자열의 경우 항상 큰 따옴표 문자를 사용하여 PEP 257의 독 스트링 규칙과 일치하십시오.

그러나 널리 사용되는 것은 자연어 문자열 (보간 포함)에 큰 따옴표를 선호하는 관행입니다. 따라서 I18N에 잠재적으로 후보가되는 모든 것이 있습니다. 기술 문자열에 대한 작은 따옴표 : 기호, 문자, 경로, 명령 줄 옵션, 기술 REGEX, ...

(예를 들어 I18N에 대한 코드를 준비 할 때 예를 사용하기 위해 큰 따옴표로 묶인 문자열을 빠르게 변환하는 반자동 REGEX를 실행합니다. gettext)


파이썬에서 문자열을 qoute 할 수있는 3 가지 방법이 있습니다 : "string" 'string' "" "string string" ""모두 동일한 결과를 생성합니다.


There is no difference in Python, and you can really use it to your advantage when generating XML. Correct XML syntax requires double-quotes around attribute values, and in many languages, such as Java, this forces you to escape them when creating a string like this:

String HtmlInJava = "<body bgcolor=\"Pink\">"

But in Python, you simply use the other quote and make sure to use the matching end quote like this:

html_in_python = '<body bgcolor="Pink">'

Pretty nice huh? You can also use three double quotes to start and end multi-line strings, with the EOL's included like this:

multiline_python_string = """
This is a multi-line Python string which contains line breaks in the 
resulting string variable, so this string has a '\n' after the word
'resulting' and the first word 'word'."""

Yes. Those claiming single and double quotes are identical in Python are simply wrong.

Otherwise in the following code, the double-quoted string would not have taken an extra 4.5% longer for Python to process:

import time

time_single = 0
time_double = 0

for i in range(10000000):
    # String Using Single Quotes
    time1 = time.time()
    str_single1 = 'Somewhere over the rainbow dreams come true'
    str_single2 = str_single1
    time2 = time.time()
    time_elapsed = time2 - time1
    time_single += time_elapsed

    # String Using Double Quotes 
    time3 = time.time()
    str_double1 = "Somewhere over the rainbow dreams come true"
    str_double2 = str_double1
    time4 = time.time()
    time_elapsed = time4 - time3
    time_double += time_elapsed

print 'Time using single quotes: ' + str(time_single)
print 'Time using double quotes: ' + str(time_double)

Output:

>python_quotes_test.py
Time using single quotes: 13.9079978466
Time using double quotes: 14.5360121727

So if you want fast clean respectable code where you seem to know your stuff, use single quotes for strings whenever practical. You will also expend less energy by skipping the shift key.

참고URL : https://stackoverflow.com/questions/143714/is-there-any-difference-between-string-and-string-in-python

반응형