Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

writing double quotes in python

Tags:

python

I would like to write the following in a text file in the following format:

The Name is from a list of names

Item "Name" RollNo

e.g

Item "Aaron" RollNo Item "Barry" RollNo

I am writing

file.write("Item" + \" + Name[i] +\") 

but getting error

like image 398
michelle Avatar asked Mar 15 '11 06:03

michelle


People also ask

What do double quotes do in Python?

What are double quotes in Python used for? A double quotation mark is to set off a direct (word-for-word) quotation. For example – “I hope you will be here,” he said. In Python Programming, we use Double Quotes for string representation.

Why do we use 3 double quotes in Python?

Spanning strings over multiple lines can be done using python's triple quotes. It can also be used for long comments in code. Special characters like TABs, verbatim or NEWLINEs can also be used within the triple quotes.

Does single or double quotes matter in Python?

In Python, such sequence of characters is included inside single or double quotes. As far as language syntax is concerned, there is no difference in single or double quoted string. Both representations can be used interchangeably.

How do you put a double quote in code?

To place quotation marks in a string in your code In Visual C# and Visual C++, insert the escape sequence \" as an embedded quotation mark.


2 Answers

With double-quote strings:

file.write("Item \"" + Name[i] + "\" ")

Or with simple quotes:

file.write('Item "' + Name[i] + '" ')

Or with triple double quotes and string interpolation:

file.write("""Item "%s" """ % Name[i])

Or with simple quotes and format:

file.write('Item "{0}"'.format(name[i]))

There are many many ways to declare string literals in Python...

like image 131
glmxndr Avatar answered Oct 21 '22 19:10

glmxndr


You can use:

s1 = 'Item "Aaron" RollNo Item "Barry" RollNo'
s2 = "Item \"Aaron\" RollNo Item \"Barry\" RollNo"

In python you can separate string with ' or " chars, and if you use " you can "escape" such char in the middle of the string with \"

like image 23
Michał Niklas Avatar answered Oct 21 '22 17:10

Michał Niklas