Programing

파이썬에서 작은 따옴표와 큰 따옴표 비교

lottogame 2020. 9. 30. 08:37
반응형

파이썬에서 작은 따옴표와 큰 따옴표 비교 [닫힌]


문서에 따르면 거의 상호 교환이 가능합니다. 다른 하나를 사용하는 문체적인 이유가 있습니까?


나는 보간에 사용되거나 자연어 메시지 인 문자열 주위에 큰 따옴표를 사용하고 작은 기호와 같은 문자열에는 작은 따옴표를 사용하지만 문자열에 따옴표가 포함되어 있거나 잊어 버린 경우 규칙을 위반합니다. 독 스트링에는 삼중 큰 따옴표를 사용하고 필요하지 않은 경우에도 정규식에는 원시 문자열 리터럴을 사용합니다.

예를 들면 :

LIGHT_MESSAGES = {
    'English': "There are %(number_of_lights)s lights.",
    'Pirate':  "Arr! Thar be %(number_of_lights)s lights."
}

def lights_message(language, number_of_lights):
    """Return a language-appropriate string reporting the light count."""
    return LIGHT_MESSAGES[language] % locals()

def is_pirate(message):
    """Return True if the given message sounds piratical."""
    return re.search(r"(?i)(arr|avast|yohoho)!", message) is not None

https://docs.python.org/2.0/ref/strings.html 에서 공식 문서 인용 :

일반 영어 : 문자열 리터럴은 일치하는 작은 따옴표 ( ') 또는 큰 따옴표 ( ")로 묶을 수 있습니다.

따라서 차이가 없습니다. 대신 사람들은 상황에 맞는 스타일을 선택 하고 일관성을 유지 하라고 말할 것입니다 . 그리고 저는 동의합니다. 이런 종류의 "컨벤션"을 생각해내는 것은 무의미합니다. 왜냐하면 당신은 새로운 이민자를 혼란스럽게 할 뿐이 기 때문입니다.


나는 '특히 '''docstrings'''내가 찾는대로 선호했다 """this creates some fluff""". 또한 스위스 독일어 키보드 'Shift없이 입력 할 수 있습니다 .

나는 PEP 257"""docstrings""" 을 준수하기 위해 트리플 따옴표를 사용하도록 변경했습니다 .


나는 Will과 함께 :

  • 텍스트의 큰 따옴표
  • 식별자처럼 작동하는 모든 것에 대한 작은 따옴표
  • 정규 표현식에 대한 큰 따옴표로 묶인 원시 문자열 리터럴
  • 독 스트링에 대한 삼중 큰 따옴표

이스케이프를 많이해야하더라도 고수하겠습니다.

따옴표로 인해 눈에 띄는 작은 따옴표로 묶인 식별자에서 가장 큰 가치를 얻습니다. 나머지 관행은 작은 따옴표로 묶인 식별자에 약간의 공간을 제공하기위한 것입니다.


가지고있는 문자열에 하나가 포함되어 있으면 다른 하나를 사용해야합니다. 예 :, "You're able to do this"또는 'He said "Hi!"'. 그 외에는 가능한 한 일관성을 유지해야합니다 (모듈 내, 패키지 내, 프로젝트 내, 조직 내).

C / C ++로 작업하는 사람들이 코드를 읽을 경우 (또는 해당 언어와 Python간에 전환하는 경우) ''단일 문자열 및 ""긴 문자열에 사용하면 쉽게 전환 할 수 있습니다. (마찬가지로 서로 바꿔서 사용할 수없는 다른 언어를 따르는 경우에도 마찬가지입니다).

나는 야생에서 본 적이 파이썬 코드를 선호하는 경향이 "이상 '하지만 약간. 한 가지 예외는 내가 본 """these"""것보다 훨씬 더 일반적이라는 것 '''these'''입니다.


세 개의 인용 된 주석은이 질문의 흥미로운 하위 주제입니다. PEP 257은 문서 문자열에 대해 삼중 따옴표를 지정합니다 . 나는 Google 코드 검색을 사용하여 빠른 검사를하고 있음을 발견 파이썬에서 트리플 따옴표가 인기로 10 배에 관하여이다 삼중 따옴표 - 코드 구글의 색인에서 131K 발생 대 1.3M. 따라서 여러 줄의 경우 삼중 큰 따옴표를 사용하면 코드가 사람들에게 더 친숙 할 것입니다.


"If you're going to use apostrophes, 
       ^

you'll definitely want to use double quotes".
   ^

그 간단한 이유 때문에 저는 항상 바깥쪽에 큰 따옴표를 사용합니다. 항상

Speaking of fluff, what good is streamlining your string literals with ' if you're going to have to use escape characters to represent apostrophes? Does it offend coders to read novels? I can't imagine how painful high school English class was for you!


Python uses quotes something like this:

mystringliteral1="this is a string with 'quotes'"
mystringliteral2='this is a string with "quotes"'
mystringliteral3="""this is a string with "quotes" and more 'quotes'"""
mystringliteral4='''this is a string with 'quotes' and more "quotes"'''
mystringliteral5='this is a string with \"quotes\"'
mystringliteral6='this is a string with \042quotes\042'
mystringliteral6='this is a string with \047quotes\047'

print mystringliteral1
print mystringliteral2
print mystringliteral3
print mystringliteral4
print mystringliteral5
print mystringliteral6

Which gives the following output:

this is a string with 'quotes'
this is a string with "quotes"
this is a string with "quotes" and more 'quotes'
this is a string with 'quotes' and more "quotes"
this is a string with "quotes"
this is a string with 'quotes'

I use double quotes in general, but not for any specific reason - Probably just out of habit from Java.

I guess you're also more likely to want apostrophes in an inline literal string than you are to want double quotes.


Personally I stick with one or the other. It doesn't matter. And providing your own meaning to either quote is just to confuse other people when you collaborate.


It's probably a stylistic preference more than anything. I just checked PEP 8 and didn't see any mention of single versus double quotes.

I prefer single quotes because its only one keystroke instead of two. That is, I don't have to mash the shift key to make single quote.


In Perl you want to use single quotes when you have a string which doesn't need to interpolate variables or escaped characters like \n, \t, \r, etc.

PHP makes the same distinction as Perl: content in single quotes will not be interpreted (not even \n will be converted), as opposed to double quotes which can contain variables to have their value printed out.

Python does not, I'm afraid. Technically seen, there is no $ token (or the like) to separate a name/text from a variable in Python. Both features make Python more readable, less confusing, after all. Single and double quotes can be used interchangeably in Python.


I chose to use double quotes because they are easier to see.


I just use whatever strikes my fancy at the time; it's convenient to be able to switch between the two at a whim!

Of course, when quoting quote characetrs, switching between the two might not be so whimsical after all...


Your team's taste or your project's coding guidelines.

If you are in a multilanguage environment, you might wish to encourage the use of the same type of quotes for strings that the other language uses, for instance. Else, I personally like best the look of '


None as far as I know. Although if you look at some code, " " is commonly used for strings of text (I guess ' is more common inside text than "), and ' ' appears in hashkeys and things like that.


I aim to minimize both pixels and surprise. I typically prefer ' in order to minimize pixels, but " instead if the string has an apostrophe, again to minimize pixels. For a docstring, however, I prefer """ over ''' because the latter is non-standard, uncommon, and therefore surprising. If now I have a bunch of strings where I used " per the above logic, but also one that can get away with a ', I may still use " in it to preserve consistency, only to minimize surprise.

Perhaps it helps to think of the pixel minimization philosophy in the following way. Would you rather that English characters looked like A B C or AA BB CC? The latter choice wastes 50% of the non-empty pixels.


I use double quotes because I have been doing so for years in most languages (C++, Java, VB…) except Bash, because I also use double quotes in normal text and because I'm using a (modified) non-English keyboard where both characters require the shift key.


' = "

/ = \ = \\

example :

f = open('c:\word.txt', 'r')
f = open("c:\word.txt", "r")
f = open("c:/word.txt", "r")
f = open("c:\\\word.txt", "r")

Results are the same

=>> no, they're not the same. A single backslash will escape characters. You just happen to luck out in that example because \k and \w aren't valid escapes like \t or \n or \\ or \"

If you want to use single backslashes (and have them interpreted as such), then you need to use a "raw" string. You can do this by putting an 'r' in front of the string

im_raw = r'c:\temp.txt'
non_raw = 'c:\\temp.txt'
another_way = 'c:/temp.txt'

As far as paths in Windows are concerned, forward slashes are interpreted the same way. Clearly the string itself is different though. I wouldn't guarantee that they're handled this way on an external device though.

참고URL : https://stackoverflow.com/questions/56011/single-quotes-vs-double-quotes-in-python

반응형