简体   繁体   中英

How do I state a code backwards and replace a letter with a certain character in python 3?

(I apologize for being unclear the first time also, WONDERFUL COMMUNITY. I'm suppose to use elif or if statements.) Below is what I have so far.

userInput = input("Write whatever you want: ")
newWord = " "

def strReplaced():
    for letter in userInput[::-1]:
        if letter == "a":
            newWord = "@"
        elif letter == "e":
            newWord = "#"
        elif letter == "i":
            newWord = "%$"
        elif letter == "0":
            newWord = "*"
        else:
            pass
    return strReplaced

print(newWord)
print(userInput)    

Must fit accordingly to these instructions, also please explain the code

  • Get user input for inputWord
  • Code to account for upper and lower case being entered
  • Assign newWord to an empty string
  • Iterate through letters in inputWord backwards. Add each letter to newWord as you iterate
  • Replace these letters: "a" with "@", "e" with "#", "i" with "%", and "o" with "*", (hint: use if, elif, else)
  • Print newWord

It must have a if and elif statement too like the code I submitted, there doesn't have to be a function. I don't think there should be a range.

Everywhere where you use newword = something , you can use += instead of = to directly append to the string. The rest of your code appears to be right according to your points (is this homework by the way?). You did forget to actually execute your function though: you have it defined but you do not use it by executing strReplaced() .

You could also remove the else: pass entirely, and newWord should probably be initialized to "" (empty string) instead of " " (string with a space). If you want to have a so-called pure function, define your function to have an argument with def strReplaced(argument_name_goes_here) .


Edit: forgot something, you are currently replacing letters (assuming you use implement the above points) but you are not adding the letters which did not have to be replaced. So don't delete the else , but replace pass with a statement that appends the letter to the new word (I think you can figure this out on your own).

Do not mess around with loops. Python 3 has a built-in translate function.

userInput = input("Write whatever you want: ")[::-1].lower()
userInput.translate(str.maketrans({'a': '@', 'e': '#', 'i': '%$', 'o': '*'}))

Write whatever you want:  This is A sentence to REPLACE
'#c@lp#r *t #cn#tn#s @ s%$ s%$ht'

Maybe this solution get easier

def test(a):
    dict_word={
        'a':'@'
        ,'e':'#'
        ,'i':'%'
        ,'o':'*'
    }
    b=a[::-1]
    print(b)
    new_word = ''
    c = []
    for i in b:
        if i in dict_word:
            res = dict_word[i]
        else:
            res=i
        c.append(res)
    new_word=''.join(c)
    return new_word


a='sdocisae'
b=test(a)
print(b)
```

You can swap out the if / elif for a dictionary.

translate = {
    "a": "@",
    "e": "#",
    "i": "%$",
    "0": "*"
}

def strreplaced(word, translate):
    newword = ''
    for letter in word:
        if letter in translate:
            newword += translate[letter]
        else:
            newword += letter
    return newword

userinput = input("Write whatever you want: ")
print(strreplaced(userinput, translate))

There are a number of good answers involving dictionaries and you will likely explore them in the future. You are on the right track though with your initial attempt.

Note the instruction say to account for upper and lower case being entered, but I am not sure what that means. I converted the input to lowercase but that might not be what you want.

If you want either an a or an A to be converted to @ and to preserve case in other instances, then you might convert each letter to lowercase prior to testing

if letter.lower() = "a":

or alternatively test for

if letter in ("a", "A"):

Here is something that might get you unstuck...

## ----------------------------
## let's pass in a parameter to this function
## ----------------------------
def strReplaced(text):
    # we will build up the result one character at a time
    # starting from an empty string
    # Note: this is not really a good method to build a string, but it will work for now.
    strReplaced = ""
    for letter in text[::-1]:
        if letter == "a":
            strReplaced += "@"
        elif letter == "e":
            strReplaced += "#"
        elif letter == "i":
            strReplaced += "%$"
        elif letter == "o":
            strReplaced += "*"
        else:
            strReplaced += letter

    return strReplaced
## ----------------------------

userInput = input("Write whatever you want: ").lower()

## ----------------------------
## Again this is not really the right way to build a string
## you will learn better ways
## ----------------------------
print("input: " + userInput)
print("output: " + strReplaced(userInput))
## ----------------------------

If I was going to write strReplaced() I would probably start with:

def strReplaced(text):
    lookup = {"a": "@", "e": "#", "i": "%", "o": "*"}
    return "".join([lookup.get(letter.lower(), letter) for letter in text[::-1]])

But I think you will come to that in a few more lessons

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM