aero26
aero26

Reputation: 155

Add empty elements to a list

phrase = "TEST PHRASE"
progress = []

for letter in phrase:
    if letter != None:
        progress.append("-")
    else:
        progress.append("")

print progress

So I want this to give me ["-","-","-","-","","-","-","-","-","-"] So that I can string.join them and get ---- ----- Basically a hidden string. But ['-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-'] is what I'm getting. No empty element to mark the space.

Upvotes: 0

Views: 14425

Answers (6)

d-coder
d-coder

Reputation: 14003

By what I understood this is what you want ?

phrase = "TEST PHRASE"
progress = []
for letter in phrase:
    if letter != " ":
        progress.append("-")
    else:
        progress.append("")
print progress
print " ".join(progress)   ## make sure you give a space between the quotes.

Output

['-', '-', '-', '-', '', '-', '-', '-', '-', '-', '-'] ## empty element in progress
- - - -  - - - - - -         ## empty element in join

Upvotes: 1

Nishant
Nishant

Reputation: 55886

While you have got what you wanted from the other answers, if all you need is to mask all the character except "white spaces", you can get less verbose using regex, like this:

>>> import re
>>> re.sub(r'[^\s]', '-', "TEST PHRASE")
'---- ------'

Upvotes: 0

Himal
Himal

Reputation: 1371

Use != ' ' and append(" ")

phrase = "TEST PHRASE"
progress = []

for letter in phrase:
     if letter != ' ':
        progress.append("-")
     else:
        progress.append(" ")

print ''.join( progress )
#---- ------

Upvotes: 1

Isuru Madusanka
Isuru Madusanka

Reputation: 373

How about change your condition like this.

  phrase = "TEST PHRASE"
    progress = []
    for letter in phrase:
        if letter == " ":
            progress.append("")
        else:
            progress.append("-")
    print(progress)

Upvotes: 0

mojo
mojo

Reputation: 4142

Comparing letter to None is not what you want. A space character isn't None. I would compare it to a space.

if letter != ' ':

Upvotes: 0

flyingfoxlee
flyingfoxlee

Reputation: 1794

use if letter != " ": instead of if letter != None.

Upvotes: 0

Related Questions