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
-
1please specify what character should be converted - because a space is a character after all..Aprillion– Aprillion2012年10月19日 00:24:09 +00:00Commented 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.DSM– DSM2012年10月19日 02:09:56 +00:00Commented Oct 19, 2012 at 2:09
3 Answers 3
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?"))
# ^^^^^ ^^^^^, ^^^^^^ ^^?
3 Comments
Are you trying to do something like this?
view = ''.join((HIDDEN if c.isalnum() else c) for c in puzzle)
Comments
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)