I'm a beginner and I'm working on an assignment where I want Python to use user input and extend the word.
If user input is monkey the output (print) should be: m-oo-nnn-kkkk-eeeee-yyyyyy
This is my start but it only outputs: m-o-n-k-e-y
Do you have any hints on how I can go forth? https://codeshare.io/8p6nB4
inp = input("Give me a word to extend: ")
index = -len(inp)
ext_inp = ''
for letter in inp:
if index < 0:
ext_inp += inp[index] + '-'
index += 1
print(ext_inp)
word_to_be_extended = input("give me a word to extern:")
word_after_extend = ''
for i in range(len(word_to_be_extended)):
word_after_extend += word_to_be_extended[i] * (i+1)
if i != len(word_to_be_extended)-1:
word_after_extend += '-'
print(word_after_extend)
Related
I am trying to use the following function to return the string with every space replaced with a %20. However, it only prints out the '%20' in each of the print statement outputs. I am also trying to omit replacing the first space in a string. Any ideas? I know that there is library and a .replace() method that exits to solve this, but I want to use a for loop and conditionals.
def urlEncode(text):
result = ''
for i in text:
if i == ' ':
i = '%20'
result = result + i
return result
print(urlEncode("Lighthouse Labs"))
print(urlEncode(" Lighthouse Labs "))
print(urlEncode("blue is greener than purple for sure"))
output is:
%20
%20%20%20%20
%20%20%20%20%20%20
Hey you need to add the characters that are not space too, right? Have a look in the edited script.
def urlEncode(text):
result = ''
for i in text:
if i == ' ':
i = '%20'
result += i
else:
result += i
return result
print(urlEncode("Lighthouse Labs"))
print(urlEncode(" Lighthouse Labs "))
print(urlEncode("blue is greener than purple for sure"))
Edit, additional answer: -how to omit first space
def urlEncode(text):
result = ''
counter = 0
for i in text:
if(counter == 0 and text[counter] == ' '):
result += i
elif i == ' ':
i = '%20'
result += i
else:
result += i
counter += 1
return result
I have a code which, after a nested for loop, provides me with a unique string in each iteration. I want to find a way to concatenate those outputs so that my final line is a single string of those unique strings. Ignoring how ugly and inefficient this code is, what steps can I take to achieve the desired result?
VOWELS = ('a','e','i','o','u','A','E','I','O','U')
ad = "Desirable unfurnished flat in quiet residential area"
# remove all vowels, unless the word starts with a vowel
def is_vowel(c):
return c in VOWELS
def mod3(ad):
testAd =ad.split()
for word in testAd:
modAd = ""
i = 0
for char in word:
if i == 0:
modAd += char
elif not is_vowel(char):
modAd += char
i+=1
print(modAd)
mod3(ad)
my output for this code:
Otherwise, when I modify my code to look like this:
But my output is:
I don't believe a .join() would work here as it's not a list type. And I can't figure out where to put a string concat + anywhere without my for loop going bonkers. Any advice?
You can create a string result where you can concatenate your each iteration result and print that. You need to add spaces after each addition of words. So, append + " " to your result variable as well.
def mod3(ad):
result = ""
testAd =ad.split()
for word in testAd:
modAd = ""
i = 0
for char in word:
if i == 0:
modAd += char
elif not is_vowel(char):
modAd += char
i+=1
result += modAd + " "
print(result)
Second option: This is my take on it:
def mod4(ad):
result = ""
testAd =ad.split()
for word in testAd:
for i, char in enumerate(word):
if i == 0:
result += char
if i > 0 and char not in VOWELS:
result += char
result += " "
print(result)
Hi I am learning python I was just trying to resolve the above example.That is make a function to change the string "oalalaeah" to "hello". Notice that 'hello' is the alternate letter starting from the back. I can do both individually. Important: I want to do it using only python functions()
`def rev_str(str1):
new_str = ''
index = len(str1)
while index > 0:
new_str += str1[index-1]
index = index - 1
return new_str`
print(rev_str('oalalaeah'))
to reverse the string to "haealalao"
later use:
def rev_alt(str2):
fin_str = ''
index = -2
while index < len(str2)-1:
fin_str += str2[index+2]
index = index + 2
return fin_str
print(rev_alt('haealalao'))
This gives me "hello" but these are 2 separate operations. I want to have 1 function that that will turn "oalalaeah" to "hello". I am sorry if this is too easy. Its driving me crazy
def rev_str(str1):
new_str = ''
index = len(str1)
while index > 0:
new_str += str1[index-1]
index = index - 1
return new_str
This is taking each letter in the string from the end to the beginning by decreasing the index by one on each iteration. Literally the only change needed to take every second letter is to decrease the index by two on each iteration:
def rev_str(str1):
new_str = ''
index = len(str1)
while index > 0:
new_str += str1[index-1]
index = index - 2 # 👈 here
return new_str
print(rev_str('oalalaeah')) # hello
The pythonic version of this is the built-in slice syntax:
print('oalalaeah'[::-2]) # hello
I'm working on a small program which takes a text input - and then places each of these items in a dictionary alongside which line they were entered on. At the moment if I enter 4 lines of text. It'll take them all out correctly, but every word will be set to the value 4 - instead of the loop it was inputted on. I've removed all the other functions from my code (remove punct, remove stopwords, stemwords, etc). to make this clearer.
from string import *
function = False
words_split = []
lineNumber=0
final_value = []
def indexer(t):
global words_split
words = t.split();
for word in words:
words_split.append(word)
def dict_print():
for keys in Dict:
output = keys + " " + str(Dict[keys][0])
i= 1
while i < len(Dict[keys]):
output = output + ", " + str(Dict[keys][i])
i = i + 1
print(output)
print("Please type a line and hit 'Enter' or type a single fullstop followed by 'Enter' to exit \n")
text = ""
while function == False :
if(text == "."):
print("The index is:")
function = True
dict_print()
else:
Dict = {}
text = input()
lineNumber += 1
for word in words_split:
if word in Dict:
if lineNumber not in Dict[word]:
Dict[word] = Dict[word] + [lineNumber]
else:
Dict[word] = [lineNumber]
indexer(text)
My global variable was causing the issue. I'll leave this up with my completed full code in case someone else runs into the same issue (:
https://repl.it/#Glaschu/AdmiredSteelCardinal
I am having trouble with the code only producing the first two letters of the first word and then attaching the 'AY' to the end while it runs. I can't seem to figure out how to correct this error.
def main():
strin = input('Enter a sentence (English): ')
strlist = strin.split()
i = 0
pigsen = ''
while i < len(strlist):
word = strlist[i]
j = 1
fc = word[0].upper()
pigword =''
while j < len(word):
pigword += word[j].upper()
j += 1
pigword += fc + 'AY'
pigsen += pigword + ' '
i +=1
print('Pig Latin: ' +str(pigsen))
main()
First, I'll assume this is just the start of a pig Latin generator and you'll add the other rules (at least a couple more) once you get this much working. Second, let's simplify the code as a way of fixing it:
def main():
sentence = input('Enter a sentence (English): ')
words = sentence.upper().split()
latin_words = []
for word in words:
first, rest = word[0], word[1:]
latin_word = rest + first + 'AY'
latin_words.append(latin_word)
print('Pig Latin:', *latin_words)
main()
USAGE
> python3 test.py
Enter a sentence (English): He complimented me on my English
Pig Latin: EHAY OMPLIMENTEDCAY EMAY NOAY YMAY NGLISHEAY
>
I would say the problem with your code is you made it too complicated.