3

I've been working on this all day to no avail, I've spent all of about 4 hours researching a possible answer because I like to discover things on my own but I can't seem to move any closer.

Im writing a function that takes a string and with this string I have to convert each character to a symbol, excluding spaces and dashes.

I've tried creating a banking system for it as well but it seems like it only iterates over the first element, does this have something to do with return?

def get_view(puzzle): 
  for elements in puzzle:
      new_ string = elements.replace(elements, "$")
      return new_string 

EDIT: I tried :

HIDDEN = "^" new_string = ""

def get_view(puzzle):
    for elements in puzzle:
    new_string = puzzle.replace(elements, HIDDEN)
    return new_string                  

And now that returns

get_view("abc") 'ab^'

Wtttfffff.

2 Answers2

5

It does have to do with return. When a return statement is encountered, the function process terminates; therefore, the for-loop of your function will always end on its first iteration.

arshajii
  • 127,459
  • 24
  • 238
  • 287
0

First you will have to define what you want to convert each letter as. Let's take an example

conversion_symbols = {'a':'$','b':'#'} # fill in the rest yourself.

# then you have to loop over the string, give gives one character at a time, covert it and
# and add to your result string and then return the result string.

def get_view(puzzle):
  new_string = ""
  for element in puzzle:
      new_string += conversion_symbols[element]
  return new_string

Is this the approach that you were trying to get to?

Senthil Kumaran
  • 54,681
  • 14
  • 94
  • 131
  • When I try that I get the error: File "", line 1, in get_view("abc") File "", line 16, in get_view new_string += HIDDEN[element] TypeError: string indices must be integers END where HIDDEN is the defined replacement. – Stacks of overflow Oct 14 '12 at 18:39
  • HIDDEN = "^" def get_view(puzzle): new_string = "" for element in puzzle: new_string += HIDDEN[element] return new_string This is the code I used when that error came up – Stacks of overflow Oct 14 '12 at 19:40