simplycoding
simplycoding

Reputation: 2977

How do I append a blank value to a Python list?

I'm trying to append a blank value to a Python list. Another value will eventually be added after that blank value as well.

This works:

foo=['NYC', 'Ny', 'Us']
print foo 
#['NYC', 'Ny', 'Us']

foo.append('')
print foo 
#['NYC', 'Ny', 'Us','']

foo.append('TRUE')
print foo
#['NYC', 'Ny', 'Us','', 'TRUE']

As you can see, all the values are essentially strings.

How do I make the first append a blank value without the quotes? I would rather have nothing if it's empty since I'll be passing this list eventually into a file and into a database.

Upvotes: 1

Views: 19803

Answers (3)

Jacob Ritchie
Jacob Ritchie

Reputation: 1401

An empty string is represented by '' in Python.

When you pass it into the database, it should eventually end up as a blank string as well.

For example :

print ''

will print a completely blank line

Upvotes: -2

turbulencetoo
turbulencetoo

Reputation: 3701

Interestingly, you could define a custom class with a __repr__ method that would give you what you want. __repr__ defines the way an opject will be represented when printed as part of a container such as a list.

>>> class BlankObj:
...  def __repr__(self):
...   return ""
...
>>> list((1,2,BlankObj(),3))
[1, 2, , 3]

This is purely academic though; it's not saving any space compared to just having a None in your list. A None object would be the best representation that a slot is empty.

Upvotes: 4

Bryan Oakley
Bryan Oakley

Reputation: 386382

The quotes are not part of the actual value in the list, so when you append "" -- and it shows as '' -- what is in the list is a zero-length string.

If instead of a zero length string you want "nothing", the python value None is the closest thing to "nothing".

The choice depends on what you mean by "blank value". For me, that's an empty string. None, however, is good if you need to distinguish between an empty string and "nothing".

Upvotes: 1

Related Questions