0

So i have a basic problem; I have the user call a function which takes a string input for example, lets say in this case apples. so the function, get_view, is called get_view('apples') and its job is to convert all characters in apples to hidden characters, example for 'apples'-->'^^^^^^', hello world would become '^^^^^ ^^^^^', and etc, my problem is that in my code below it does convert all letters and numbers and etc but it does not leave the empty space present between hello world, and it also does not consider ('). How can i modify my code to make it fully functional?

code :

def get_view(puzzle):

    view = puzzle
    length = len(puzzle)
    for index in range(0,length):
        if ((puzzle[index]) != '' or '-' ):
            view = view[: index] + HIDDEN + view[index+1:]

HIDDEN = '^' (its a constant)

Thank you, new to the website <3

2
  • 1
    please specify what character should be converted - because a space is a character after all.. Commented Oct 19, 2012 at 0:24
  • @user1757870: Please don't destroy your own questions -- it significantly lowers the value of the answers that people spent time working to craft. Commented Oct 19, 2012 at 2:09

3 Answers 3

2

i use regex functions like re.sub() for most non-trivial string operations, like this:

import re
print(re.sub("[a-zA-Z0-9_']", "^", "Hello world, what's up?"))
#                                   ^^^^^ ^^^^^, ^^^^^^ ^^?
Sign up to request clarification or add additional context in comments.

3 Comments

Add , flags=re.IGNORECASE or update your regex to get uppercase letter.
"\S" would do anything that isn't a space
@JasonSperske thanks for the comments, the question isn't clear about what characters should and should not be "hidden"
1

Are you trying to do something like this?

view = ''.join((HIDDEN if c.isalnum() else c) for c in puzzle)

Comments

1

Assuming then that you do not want to alter white space characters (space, tab, new-line), this is one way to do it using a for loop:

def get_view(puzzle, hide_char='^'):
    view = []
    for c in puzzle:
        if not c.isspace():
            view.append(hide_char)
        else:
            view.append(c)
    return ''.join(view)

Alternatively (and better) is to use a list comprehension:

def get_view(puzzle, hide_char='^'):
    view = [c if c.isspace() else hide_char for c in puzzle]
    return ''.join(view)

or just:

def get_view(puzzle, hide_char='^'):
    return ''.join(c if c.isspace() else hide_char for c in puzzle)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.