Is there any difference between "string" and 'string' in Python? [duplicate]
In PHP, a string enclosed in "double quotes" will be parsed for variables to replace whereas a string enclosed in 'single quotes' will not. In Python, does this also apply?
Asked by: Catherine748 | Posted: 24-09-2021
Answered by: Eric514 | Posted: 25-10-2021
2.4.1. String and Bytes literals
...In plain English: Both types of literals can be enclosed in matching single quotes (
') or double quotes (
"). They can also be enclosed in matching groups of three single or double quotes (these are generally referred to as triple-quoted strings). The backslash (
\) character is used to escape characters that otherwise have a special meaning, such as newline, backslash itself, or the quote character...
Python is one of the few (?) languages where ' and " have identical functionality. The choice for me usually depends on what is inside. If I'm going to quote a string that has single quotes within it I'll use double quotes and visa versa, to cut down on having to escape characters in the string.
"this doesn't require escaping the single quote" 'she said "quoting is easy in python"'
This is documented on the "String Literals" page of the python documentation:
- http://docs.python.org/2/reference/lexical_analysis.html#string-literals (2.x)
- http://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals (3.x)
In some other languages, meta characters are not interpreted if you use single quotes. Take this example in Ruby:
irb(main):001:0> puts "string1\nstring2" string1 string2 => nil irb(main):002:0> puts 'string1\nstring2' string1\nstring2 => nil
In Python, if you want the string to be taken literally, you can use raw strings (a string preceded by the 'r' character):
Answered by: Nicole516 | Posted: 25-10-2021
>>> print 'string1\nstring2' string1 string2 >>> print r'string1\nstring2' string1\nstring2
Single and double quoted strings in Python are identical. The only difference is that single-quoted strings can contain unescaped double quote characters, and vice versa. For example:
'a "quoted" word' "another 'quoted' word"
Then again, there are triple-quoted strings, which allow both quote chars and newlines to be unescaped.
You can substitute variables in a string using named specifiers and the locals() builtin:
Answered by: Gianna469 | Posted: 25-10-2021
name = 'John' lastname = 'Smith' print 'My name is %(name)s %(lastname)s' % locals() # prints 'My name is John Smith'
The interactive Python interpreter prefers single quotes:
>>> "text" 'text' >>> 'text' 'text'
This could be confusing to beginners, so I'd stick with single quotes (unless you have different coding standards).Answered by: Michelle770 | Posted: 25-10-2021
The difference between " and ' string quoting is just in style - except that the one removes the need for escaping the other inside the string content.
In Python, single-quoted strings and double-quoted strings are the same. This PEP does not make a recommendation for this. Pick a rule and stick to it. When a string contains single or double quote characters, however, use the other one to avoid backslashes in the string. It improves readability.
For triple-quoted strings, always use double quote characters to be consistent with the docstring convention in PEP 257 .
Widely used however is the practice to prefer double-quotes for natural language strings (including interpolation) - thus anything which is potentially candidate for I18N. And single quotes for technical strings: symbols, chars, paths, command-line options, technical REGEXes, ...
(For example, when preparing code for I18N, I run a semi-automatic REGEX converting double quoted strings quickly for using e.g.
There are 3 ways you can qoute strings in python: "string" 'string' """ string string """ they all produce the same result.Answered by: Walter852 | Posted: 25-10-2021
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:
Answered by: Ryan217 | Posted: 25-10-2021
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)
>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.Answered by: Walter806 | Posted: 25-10-2021
datetime - What is the simplest way to find the difference between 2 times in python?
I have 2 time values which have the type datetime.time. I want to find their difference. The obvious thing to do is t1 - t2, but this doesn't work. It works for objects of type datetime.datetime but not for datetime.time. So what is the best way to do this?
algorithm - Average difference between dates in Python
I have a series of datetime objects and would like to calculate the average delta between them. For example, if the input was (2008-10-01 12:15:00, 2008-10-01 12:25:00, 2008-10-01 12:35:00), then the average delta would be exactly 00:10:00, or 10 minutes. Any suggestions on how to calculate this using Python?
c# - Text difference algorithm
I need an algorithm that can compare two text files and highlight their difference and ( even better!) can compute their difference in a meaningful way (like two similar files should have a similarity score higher than two dissimilar files, with the word "similar" defined in the normal terms). It sounds easy to implement, but it's not. The implementation can be in c# or python. Thanks.
What is the difference between Ruby and Python versions of"self"?
I've done some Python but have just now starting to use Ruby I could use a good explanation of the difference between "self" in these two languages. Obvious on first glance: Self is not a keyword in Python, but there is a "self-like" value no matter what you call it. Python methods receive self as an explicit argument, whereas Ruby does not. Ruby sometimes has methods explicitly d...
python - What's the difference between all of the os.popen() methods?
I was looking at the Python documentation and saw that there are 4-5 different versions of popen(), e.g. os.popen(), os.popen2(), etc. Apart from the fact that some include stderr while others don't, what are the differences between them and when would you use each one? The documentation didn't really explain it very wel...
datetime - Python's timedelta: can't I just get in whatever time unit I want the value of the entire difference?
I am trying to have some clever dates since a post has been made on my site ("seconds since, hours since, weeks since, etc..") and I'm using datetime.timedelta difference between utcnow and utc dated stored in the database for a post. Looks like, according to the docs, I have to use the days attribute AND the seconds attribute, to get the fancy date strings I want. Can't I just get in whatever time unit I ...
Difference between the use of double quote and quotes in python
This question already has answers here:
python - How to tell the difference between an iterator and an iterable?
In Python the interface of an iterable is a subset of the iterator interface. This has the advantage that in many cases they can be treated in the same way. However, there is an important semantic difference between the two, since for an iterable __iter__ returns a new iterator object and not just self. How ...
Difference between class (Python) and struct (C)
I'm new to python. I've studied C and I noticed that that the C structure (struct) seemed to have the same task as "class" in python. So what is, conceptually, the difference?
syntax - What's the difference between "2*2" and "2**2" in Python?
What is the difference between the following statements? Statement 1: var=2**2*3 Statement 2: var2=2*2*3 I see no difference. This raises the following question. Why is Statement 1 used if we can use Statement 2?