Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python string good practise: ' vs " [duplicate]

Possible Duplicate:
Single quotes vs. double quotes in Python

I have seen that when i have to work with string in Python both of the following sintax are accepted:

mystring1  = "here is my string 1"
mystring2  = 'here is my string 2'

Is anyway there any difference?

Is it by any reason better use one solution rather than the other?

Cheers,

like image 630
Stefano Avatar asked Oct 28 '11 12:10

Stefano


People also ask

Is it better to use single or double quotes Python?

Use single-quotes for string literals, e.g. 'my-identifier' , but use double-quotes for strings that are likely to contain single-quote characters as part of the string itself (such as error messages, or any strings containing natural language), e.g. "You've got an error!" .

Does += work for strings in Python?

+= operatorYou can append another string to a string with the in-place operator, += . The string on the right is concatenated after the string variable on the left.

Does using the += operator to concatenate strings violate Python's string immutability Why or why not?

It violates the rules of how ID values and += are supposed to work - the ID values produced with the optimization in place would be not only impossible, but prohibited, with the unoptimized semantics - but the developers care more about people who would see bad concatenation performance and assume Python sucks.

What does str () do in Python?

The str() function converts values to a string form so they can be combined with other strings. The "print" function normally prints out one or more python items followed by a newline.


1 Answers

No, there isn't. When the string contains a single quote, it's easier to enclose it in double quotes, and vice versa. Other than this, my advice would be to pick a style and stick to it.

Another useful type of string literals are triple-quoted strings that can span multiple lines:

s = """string literal...
...continues on second line...
...and ends here"""

Again, it's up to you whether to use single or double quotes for this.

Lastly, I'd like to mention "raw string literals". These are enclosed in r"..." or r'...' and prevent escape sequences (such as \n) from being parsed as such. Among other things, raw string literals are very handy for specifying regular expressions.

Read more about Python string literals here.

like image 77
NPE Avatar answered Nov 09 '22 01:11

NPE