This question already has answers here:
Single quotes vs. double quotes in Python [closed]
(19 answers)
Closed 9 years ago.
Python's Philosophy:
....
Simple is better than complex.
....
So why does it use both double quote " " and single quote ' ' to indicate something is a string literal.
I was lost when I typed:
x = "aa"
x
And saw:
'aa'
But not:
"aa"
When I saw the above philosophy, I doubted it. It needs some explanations.
This isn't complex at all. In fact, it's rather helpful.
Both '' and "" can be used in python. There's no difference, it's up to you.
In your example, when you type x, you are given the representation of the string (i.e, it's equivalent to print repr(x)). It wouldn't have mattered if you did x = 'aa'
I like to use either for cases such as:
print 'Bill said, "Hey!"'
print "I'm coming!"
If we used " for the first example, then there would be an error because Python would interpret it as "Bill said, ".
If we used ' for the second example, then there would be an error because Python would interpret it as 'I'
Of course, you could just escape the apostrophes, but beautiful is better than ugly.
You can use "" to be able to write "I'm legend" for example.
Related
This question already has answers here:
In Python, is it possible to escape newline characters when printing a string?
(3 answers)
Closed 1 year ago.
I want to print the specific characters \n in python and C language. Of course its the newline character so every time I say print("\n") or printf("\n") it simply prints whitespace.
What I want are the specific characters \ and n as the output.
Could someone please help with this?
In C you need to add another "\" to your code like this.
#include <stdio.h>
main() {
printf("\\n");
}
For Python you can use repr
>>> string = "\n"
>>> print(repr(string))
'\n'
You can use repr() to represent a raw string.
print(repr('\n'))
This question already has answers here:
Why do backslashes appear twice?
(2 answers)
Closed last month.
I have a string like this:
'\\xac\\x85'
and I want to encode these string like this another:
'\xac\x85'
I tried a lot of things like encode tu utf-8, replace \\x, etc. But when I print the result it always is with \\x.
Any idea?
'\\xac\\x85' is the literal representation of '\xac\x85'. So you dont have to do any translation
>>> print ('\\xac\\x85')
\xac\x85
I made this function when I had the same issue
I included a little demo! Hope this helps people!
def FixSlash(string):
strarr = string.split("\\x");
string = strarr[0]
for i in strarr[1:]:
string+=chr(int(i[:2],16))+''.join(i[2:])
return string```
my_string = FixSlash("my string has '\\xac\\x85' in it")
print(my_string) # returns "my string has '¬' in it" \x85 acts like a new line
print(my_string.encode("latin1")) # returns b"my string has '\xac\x85' in it" proving the '\\x' to '\x' was successful!
#TIP: never trust UTF-8 for byte encoding!!
This question already has answers here:
Having both single and double quotation in a Python string
(9 answers)
Closed 5 years ago.
I'd like to save the following characters 'bar" as a string variable, but it seems to be more complicated than I thought :
foo = 'bar" is not a valid string.
foo = ''bar"' is not a valid string either.
foo = '''bar"'' is still not valid.
foo = ''''bar"''' actually saves '\'bar"'
What is the proper syntax in this case?
The last string saves '\'bar"' as the representation, but it is the string you're looking for, just print it:
foo = ''''bar"'''
print(foo)
'bar"
when you hit enter in the interactive interpreter you'll get it's repr which escapes the second ' to create the string.
Using a triple quoted literal is the only way to define this without explicitly using escapes. You can get the same result by escaping quotes:
print('\'foo"')
'foo"
print("'foo\"")
'foo"
This question already has answers here:
Closed 11 years ago.
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,
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.
While it's true that there is no difference between one and the other, I encountered a lot of the following behavior in the opensource community:
" for text that is supposed to be read (email, feeback, execption, etc)
' for data text (key dict, function arguments, etc)
triple " for any docstring or text that includes " and '
No. A matter of style only. Just be consistent.
I tend to using " simply because that's what most other programming languages use.
So, habit, really.
There's no difference.
What's better is arguable. I use "..." for text strings and '...' for characters, because that's consistent with other languages and may save you some keypresses when porting to/from different language. For regexps and SQL queries, I always use r'''...''', because they frequently end up containing backslashes and both types of quotes.
Python is all about the least amount of code to get the most effect. The shorter the better. And ' is, in a way, one dot shorter than " which is why I prefer it. :)
As everyone's pointed out, they're functionally identical. However, PEP 257 (Docstring Conventions) suggests always using """ around docstrings just for the purposes of consistency. No one's likely to yell at you or think poorly of you if you don't, but there it is.
This question already has answers here:
Closed 12 years ago.
Possible Duplicates:
Difference between the use of double quote and quotes in python
Single quotes vs. double quotes in Python
So I am now learning python, and was creating a function. What is the difference between using ' and ". I will create a sample function below to exemplify my question.
def question(variable):
print variable
now what is the difference between calling
question("hello")
and
question('hello')
they both print hello, but why can I use both? Is it just because python is flexible? I was confused because ' is usually used for chars where as " is for strings for java right?
Both are equal and what you use is entirely your preference.
As far as the char vs string thing is concerned, refer to the Zen of Python, (PEP 20 or import this)
Special cases aren't special enough to break the rules.
A string of length 1 is not special enough to have a dedicated char type.
Note that you can do:
>>> print 'Double" quote inside single'
Double" quote inside single
>>> print "Single' quote inside double"
Single' quote inside double
" is useful when you have ' into the string and vice versa
Python does not have that restriction of single quotes for chars and double quotes for strings.
As you can see here the grammar explicitly allows both for strings.
http://docs.python.org/reference/lexical_analysis.html#string-literals