How do you reverse this string using a for loop - python

how do I modify the code so that it reverses the string?
str = "pizza"
def letterReverse(word):
newStr = ""
for letter in word:
newStr += letter
return newStr
print(letterReverse(str))

The problem is in your line newStr += letter. That adds the new letter to the right end of newStr, but you want to add it to the left side. So change that line to newStr = letter + newStr. You also should avoid using str as a variable name, so I changed it to oldstr. Your new code is then
oldstr = "pizza"
def letterReverse(word):
newStr = ""
for letter in word:
newStr = letter + newStr
return newStr
print(letterReverse(oldstr))
The output from that is what you want:
azzip

You can try this:
str = "pizza"
new_str = str[::-1]
If you want to modify your code just add [::-1] in your loop:
str = "pizza"
def letterReverse(word):
newStr = ""
for letter in word[::-1]:
newStr += letter
return newStr
print(letterReverse(str))

Related

How do I fix this code about index string?

I make a function to input string and return with head and tail with two indexes without space and punctuation. but it's return only "empty string"
def hello(word):
str_cnt = ""
for letter in word:
if letter not in string.whitespace and letter not in string.punctuation:
str_cnt += letter
if len(str_cnt) < 2 :
return "empty string"
else:
return str_cnt[:2] + str_cnt[-2:]
word = input("Input String : ")
result = hello(word)
print("Result: ",result)
I expect when I input "hello world!", and the actual output is "held"
or "Hi!" = "HiHi".
The problem is simply incorrect indentation:
import string
def hello(word):
str_cnt = ""
for letter in word:
if letter not in string.whitespace and letter not in string.punctuation:
str_cnt += letter
if len(str_cnt) < 2:
return "empty string"
return str_cnt[:2] + str_cnt[-2:]
word = input("Input String: ")
result = hello(word)
print("Result: ", result)
Indentation is everything in Python!
> python3 test.py
Input String: hello world!
Result: held
>
However, if the input is long, this is the wrong way to go about the problem. We test a lot of characters we'll never use against the whitespace and punctuation lists. Instead we should grab the first two valid characters from either end of the list and ignore the middle. Something like:
def hello(word):
unwanted = string.whitespace + string.punctuation
str_start = ""
for letter in word:
if letter not in unwanted:
str_start += letter
if len(str_start) == 2:
break
if len(str_start) < 2:
return "empty string"
str_end = ""
for idx in range(len(word) - 1, -1, -1):
if word[idx] not in unwanted:
str_end = word[idx] + str_end
if len(str_end) == 2:
break
return str_start + str_end
EXAMPLE
> python3 test2.py
Input String: telecommunications!
Result: tens
>
The letters 'lecommunicatio' were never tested as they had no effect on the eventual outcome.
You miss-indented the last if block:
import string
def hello(word):
str_cnt = ""
for letter in word:
if letter not in string.whitespace and letter not in string.punctuation:
str_cnt += letter
if len(str_cnt) < 2 :
return "empty string"
else:
return str_cnt[:2] + str_cnt[-2:]
word = input("Input String : ")
result = hello(word)
print("Result: ",result)
Example output:
Input String : Hello World!
Result: Held
Your issue is that you return after the first iteration through the work, no matter what.
Move the return nogic after the logic:
def hello(word):
str_cnt = ""
for letter in word:
if letter not in string.whitespace and letter not in string.punctuation:
str_cnt += letter
if len(str_cnt) < 2 :
return "empty string"
else:
return str_cnt[:2] + str_cnt[-2:]
The problem is indentation as everyone says, after correcting which it works. I would do it more pythonically as:
def hello(word):
w = ''.join([x for x in word if x not in string.whitespace and x not in string.punctuation])
return w[:2] + w[-2:] if len(w) > 1 else 'empty string'
Usage:
>>> hello('hello world!')
held

How to encrypt and decrypt?

In Python3 I must create two functions, substitutionEncrypt and substitutionDecrypt.
substitutionEncrypt must be revised so that it removes all spaces of plain text before being encrypted and that it will generate a cipher key from a password.(Call genKeyFromPass). psw will replace key as a parameter in the function header.
substitutionDecrypt will have two parameters(cipherText, psw)
I have been given the following codes. it should return the original plainText with spaces removed.
Finally, write a top-level function, main. main should (a) use Python’s built-in input function to get a string to encrypt and a password; (b) call substitutionEncrypt to encrypt the input string; (c) print the value returned by substitutionEncrypt; (d) call substitutionDecrypt to convert the value returned by substitutionEncrypt back to
plaintext; (e) print the value returned by substitutionDecrypt.
Note: subEncrypt and subDecrypt will need to call genKeyFromPass, which call removeDupes and removeMatches. I have been given the codes below.
defSubstitutionEncrypt(plainText, key):
alphabet = "abcdefghijklmnopqrstuvwxyz "
plainText = plainText.lower()
cipherText = " "
for ch in plainText:
idx = alphabet.find(ch)
cipherText = cipherText + key[idx]
return cipherText
def removeDupes(myString):
newStr = " "
for ch in myString:
if ch not in newStr:
newStr = newStr + ch
return newStr
def removeMatches(myString, removeString):
newStr = " "
for ch in myString:
if ch not in removeString:
newStr = newStr + ch
return newStr
def genKeyFromPass(password):
key = 'abcdefghijklmnopqrstuvwxyz'
password = removeDupes(password)
lastChar = password[-1]
lastIdx = key.find(lastChar)
afterString = removeMatches(key[lastIdx+1:], password)
beforeString = removeMatches(key[:lastIdx], password)
key = password + afterString + beforeString
return key
From this code I have created:
def substitutionEncrypt(plainText, psw):
alphabet = "abcdefghijklmnopqrstuvwxyz "
newStr = plainText.lower()
cipherText = " "
genKeyFromPass(newStr)
for ch in newStr:
idx = alphabet.find(ch)
cipherText = cipherText + genKeyFromPass(psw)[idx]
return cipherText.replace(" ","")
def genKeyFromPass(psw):
key = 'abcdefghijklmnopqrstuvwxyz'
psw = removeDupes(psw)
lastChar = psw[-1]
lastIdx = key.find(lastChar)
afterString = removeMatches(key[lastIdx+1:], psw)
beforeString = removeMatches(key[:lastIdx], psw)
key = psw + afterString + beforeString
return key
def removeDupes(myString):
newStr = " "
for ch in myString:
if ch not in newStr:
newStr = newStr + ch
return newStr
def removeMatches(myString, removeString):
newStr = " "
for ch in myString:
if ch not in removeString:
newStr = newStr + ch
return newStr
print(substitutionEncrypt('the quick brown fox', 'ajax'))
I get "nukobjdualhqguyhr" as an output.
The output examples are:
subEncrypt('the quick brown fox', 'ajax')
'qdznrexgjoltkblu'
subDecrypt('qdznrexgjoltkblu', 'ajax')
'thequickbrownfox'
What am I doing wrong with my code? I have been having trouble with calling a value from another function(calling key from genKeyFromPass). Its the line before the return statement in the substitutionEncrypt. Also, how would I go about the substitutionDecrypt? I've gotten this far:
def substitutionDecrypt(cipherText, psw):
alphabet = 'abcdefghijklmnopqrstuvwxyz'
newStr = cipherText.lower()
plainText = " "
genKeyFromPass(cipherText)
for ch in cipherText:
idx = alphabet.find(ch)
return plainText.replace(" ","")

CodeHS Python, remove all from string

I am using CodeHS for my Computer Science Principles class and one of the problems in the Strings section is really confusing me. We have to remove all of one string from another string.
These are the official instructions:
Write a function called remove_all_from_string that takes two strings, and returns a copy of the first string with all instances of the second string removed. You can assume that the second string is only one letter, like "a".
We are required use:
A function definition with parameters
A while loop
The find method
Slicing and the + operator
A return statement
We are expected to only have to use those 5 things to make it work.
I attempted to write this program but my function doesn't do anything and I am really stumped.
def remove_all_from_string(word, letter):
while letter in word:
x=word.find(letter)
if x==-1:
continue
else:
return x
print word[:x] + word[x+1:]
remove_all_from_string("alabama", "a")
The easiest way to do this would obviously just be
def remove_all_from_string(word, letter):
return word.replace(letter, "")
However, considering the parameters, another way we could do this is like so:
def remove_all_from_string(word, letter):
while letter in word:
x=word.find(letter)
if x == -1:
continue
else:
word = word[:x] + word[x+1:]
return word
You could run this and print it by typing
>>> print(remove_all_from_string("Word Here", "e"))
#returns Word hr
def remove_all_from_string(word, letter):
while letter in word:
x=word.find(letter)
if x == -1:
continue
else:
word = word[:x] + word[x+1:]
return word
print(remove_all_from_string("hello", "l"))
def remove_all_from_string(word, letter):
letters = len(word)
while letters >= 0:
x=word.find(letter)
if x == -1:
letters = letters - 1
continue
else:
# Found a match
word = word[:x] + word[x+1:]
letters = letters - 1
return word
remove_all_from_string("alabama", "a")
I have this so far and it keeps saying that message is not defined and when I define it with find_secret_word it says "find_secret_word" is not defined, what do I do?
This is my code:
`word = "bananas"
letter = "na"
index = word.find(letter)
def remove_all_from_string(word, letter):
while letter in word:
x=word.find(letter)
if x == -1:
continue
else:
word = word[:x] + word[x+1:]
return word
word = word[:index] + word[index+len(letter):]
print(remove_all_from_string("hello", "l"))
def find_secret_word(message):
while True:
return hidden_word
hidden_word = "iCjnyAyT"
for letter in message:
if letter.upper():
hidden_word = hidden_word + letter
print (find_secret_word(message))`

Recursive function to remove vowels

I'm trying to write a recursive program that returns a string of letters from a word that are non vowels. My code right now print's out all of the non vowels of "University" but never ends . Any ideas?
def removeVowels9(aString):
if len(aString) == 0:
return newString
else:
newString = aString[1:len(aString) + 1]
firstLetter = aString[0]
#print(firstLetter)
if firstLetter in "aeiouAEIOU":
return removeVowels9(newString)
else:
newString = newString + firstLetter
print(newString)
return removeVowels9(newString)
Clearly you are never hitting the base case, because you would get a NameError (newString hasn't been defined).
Why? Let's look at your third case:
else: # starts with consonant
newString = newString + firstLetter # add first letter to the end?
return removeVowels9(newString) # repeat
once you've removed all of the vowels, this just keeps on looping the consonants, as you should have seen from your outputs:
>>> removeVowels9("University")
iversityn
ersitynv
sitynvr
itynvrs
ynvrst # all vowels gone
nvrsty
vrstyn
rstynv
stynvr
tynvrs
ynvrst # just keeps looping
...
Here is the minimal fix:
>>> def removeVowels9(aString):
if len(aString) == 0:
return aString # aString, not newString
else:
newString = aString[1:len(aString) + 1]
firstLetter = aString[0]
#print(firstLetter)
if firstLetter in "aeiouAEIOU":
return removeVowels9(newString)
else:
return firstLetter + removeVowels9(newString) # add first letter back at start, after processing rest
>>> removeVowels9("University")
'nvrsty'
But this could be much neater:
def remove_vowels(s):
"""Recursively remove vowels from the input."""
if not s: # empty string
return s
elif s[0] in "aeiouAEIOU": # first character is vowel
return remove_vowels(s[1:]) # skip first character and process rest
return s[0] + remove_vowels(s[1:]) # return first character and process rest
Which does:
>>> remove_vowels("University")
'nvrsty'
Note compatibility with the style guide for variable names etc..

Codecademy Practice Makes Perfect 10/15 (Word Censoring)

I'm on Codecademy, the section called "Practice Makes Perfect", on problem 10/15, the word-censoring one. The problem goes like this:
Write a function called censor that takes two strings, text and word, as input. It should return the text with the word you chose replaced with asterisks.
My idea was to do this:
def censor(text, word):
length_of_word = len(word)
word_now_censored = '*' * length_of_word
wordlist = text.split()
for item in wordlist:
if item == word:
item = word_now_censored
return " ".join(wordlist)
But, so it seems, changing the value of item in the for loop doesn't change the value of the item in the list.
I thought another way could be to use a while loop, going from i = 0 to i < len(wordlist), and then modify wordlist[i] as needed, but I'd just like to understand why my for-loop method doesn't work.
Change it to this:
for index, item in enumerate(wordlist):
if item == word:
wordlist[index] = word_now_censored
You could simply use re.sub to replace all instances of word:
import re
def censor(text, word):
return re.sub(r'\b{}\b'.format(word), '*' * len(word), text)
Your observation is right
changing the value of item in the for loop doesn't change the value of the item in the list.
There are many ways to go about this. Here is one way. Create another variable new_words_list. Append the word from wordlist to new_words_list if it not word. Else append word_now_censored to new_words_list.
Which translates to:
def censor(text, word):
length_of_word = len(word)
word_now_censored = '*' * length_of_word
wordlist = text.split()
new_words_list = []
for item in wordlist:
if item == word:
new_words_list.append(word_now_censored)
else:
new_words_list.append(item)
return " ".join(new_words_list)
def censor(text,word):
text=list(text)
for n in range(0,len(text)):
i=0
while 1==1:
for i in range(0,len(word)):
if text[n+i]==word[i]:
i+=1
else:
break
if i==len(word):
for m in range(0,i):
text[n+m]='*'
else:
break
n+=i
return "".join(text)
print censor("this hack is wack hack", "hack")
Here is another version:
def censor(text, word):
lst = text.split()
while word in lst:
index = lst.index(word)
lst.remove(word)
lst.insert(index,'*' * len(word))
return " ".join(lst)
censor takes two strings, text and word, as input. It returns the text with the word you chose replaced with asterisks.
def censor(text,word):
result = ""
count = 0
no_of_stars = 0
split_list = text.split()
for i in split_list:
count += 1
if(i==word):
result += "*" * len(i)
else:
result +=i
if(count != len(split_list)):
result += " "
return result
Here's my version. Simply build a new word of asterisks the same length as the word, then replace it.
def censor(text, word):
if word in text:
blabber = ""
while True:
blabber += "*"
if len(blabber) == len(word):
break
return text.replace(word, blabber)
def censor(text,word):
res = text.split()
temp = ""
for i,j in enumerate(res):
if j == word:
res[i] = "*" * len(word)
return " ".join(res)
Just solved it and this was my solution:
def censor(text, word):
textList = text.split()
for index, var in enumerate(textList):
if var == word:
textList[index] = "*" * len(word)
return " ".join(textList)
def censor(text,word) :
c=''
for i in text.split() :
if i == word :
i = "*" * len(word)
c += ' ' + i
else :
c += ' ' + i
return c
print censor("this hack is wack hack", "hack")
def censor(text, word):
lista=[]
for i in text.split():
if i==word:
lista+=['*'*len(word)]
else:
lista+=[i]
return ' '.join(lista)
def censor(text, word):
new_text = text.split()
ctext = []
for item in new_text:
if item == word:
item = "*" *len(word)
ctext.append(item)
return " ".join(ctext)
def censor(text, word):
a = word
b = len(a)
for a in text:
text = text.replace(word, "*"*b)
return text
My idea was just:
def censor(text, word):
answer = text.replace(word, "*"*len(word))
return answer
This is might be simple one but I think simple is good. And I didn't have to use any loop, is it good?
If you like my answer, please let me know, I'll be really happy. Thank you
I've made it quite simple and I don't see why no one mentioned this.
def censor(text, word):
return text.replace(word,"*" * len(word))
I'll appreciate it if you will take a look at this one.
def censor(text, word):
if word in text:
return text.replace(word, '*' * len(word))

Categories

Resources