13
votes

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

3
While this is an easy case to diagnose without the actual error, generally, providing the error and full stack trace can assist in helping you solve your problems. - Josh Smeaton

3 Answers

26
votes

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...

8
votes

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 \"

0
votes

You can also try the triple single quotes to have your string preserve the double quoted

str = '''Item "Aaron" RollNo Item "Barry" RollNo'''

output will be like this

preserve the double quoted word in python string