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
Related
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)
The question was: Return a sentence with the words reversed
>>> master_yoda('I am home')
'home am I'
It will eventually reverse the words of the line.
I am learning and performing Python in Jupyter Notebook.
def master_yoda(string):
l = string.split()``
p = len(string) - 1
final = ''
while p<0:
final = final + ' ' + s[p]
p = p-1
print (final)
master_yoda('Hello my name is Aryan')
The output is nothing..
No syntax errors , but still no output ...
Perhaps you should try this.
def master_yoda(string):
reversed_list = string.split(' ')
reversed_list.reverse()
reversed_string = ' '.join(reversed_list)
print(reversed_string)
master_yoda("i am home")
The big problem with the code is that you were testing for p < 0 but since p starts off with a positive value, the code never enters the while loop. You should really have been testing for p >= 0. The following code should do what you want, they way you seem to want it to:
def master_yoda(string):
l = string.split()
p = len(l) - 1
final = l[p]
p -= 1
while p >= 0:
final += ' ' + l[p]
p -= 1
return final
Note that this implementation fails if an empty string is passed as input. I tried to keep the code in the spirit of your own code and checking for an empty string would make it more complex. The simplest and most robust solution would be:
def master_yoda(string):
return ' '.join(reversed(string.split()))
I'm trying to implement run length encoding into python with this code.
When I run it I get string index out of range error, not sure what is causing the error though
text="aaabbbcc"
def encode(text):
prev = text[0]
lentext = len(text)
i = 1
while prev == text[i] and i < lentext:
i += 1
return prev + str(i) + encode(text[i:])
print(encode(text))
Before you can check if i is less than the text length, you already try to access the ith element of text, which causes the exception. Instead, write your while loop as:
while i < lentext and prev == text[i]:
This will make sure i is in range before trying to access that index of text.
Also note that if you are going to use a recursive algorithm, you need a base case to exit the chain of recursive calls from. Probably something like the following at the top of your function:
if not text:
return ""
So all together:
text="aaabbbcc"
def encode(text):
if not text:
return ""
prev = text[0]
lentext = len(text)
i = 1
while i < lentext and prev == text[i]:
i += 1
return prev + str(i)+ encode(text[i:])
print(encode(text))
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
code for a function which increments a string, to create a new string. If the string already ends with a number, the number should be incremented by 1. If the string does not end with a number the number 1 should be appended to the new string.
The output is correct but it is showing a String index out of range error. Can someone help me on where and how the string index is out of range?
test cases,expected output:
(increment_string("foo"), "foo1"),(increment_string("foobar001"), "foobar002"),(increment_string("foobar1"), "foobar2"),(increment_string("foobar00"), "foobar01"),("foobar99"), "foobar100"),("foobar099"), "foobar100"),(increment_string(""), "1")
def increment_string(strng):
if strng[-1].isdigit():
exp_strng=strng[::-1]
new_strng=""
new_strng1=""
for i in exp_strng:
if i.isdigit():
new_strng+=i
else:
break
new_strng=new_strng[::-1]
new_strng1=int(new_strng)+1
new_strng1='{num:{fill}{width}}'.format(num=new_strng1, fill='0', width=len(new_strng))
return(strng[:-len(new_strng)]+new_strng1)
else:
strng+="1"
return(strng)
Since you gave us more information on the test cases given, you can bypass the edge case of an empty string by modifying the if statement:
def increment_string(strng):
# Add it here #
if strng == "":
return "1"
elif strng[-1].isdigit():
exp_strng = strng[::-1]
new_strng = ""
new_strng1 = ""
for i in exp_strng:
if i.isdigit():
new_strng += i
else:
break
new_strng = new_strng[::-1]
new_strng1 = int(new_strng) + 1
new_strng1 = '{num:{fill}{width}}'.format(num=new_strng1, fill='0', width=len(new_strng))
return strng[:-len(new_strng)] + new_strng1
else:
strng += "1"
return strng
If think this would be a better solution to your problem:
from re import search
def increment_string(s):
number = search('\d+$', s)
if number != None:
number = number.group()
first_part = s.split(number)[0]
return first_part + str(int(number)+1)
else:
return s + '1'
I don't know what you want when the number is 9 though: 0 or 10. This code produces 10.
the error was caused when empty string is passed. and I resolved it by adding one more if else:(thanks to Skam)
def increment_string(strng):
if len(strng)>0:
if strng[-1].isdigit():
exp_strng=strng[::-1]
new_strng=""
new_strng=""
for i in exp_strng:
if i.isdigit():
new_strng+=i
else:
break
new_strng=new_strng[::-1]
new_strng1=int(new_strng)+1
new_strng1=str(new_strng1)
new_strng1=new_strng1.zfill(len(new_strng))
return(strng[:-len(new_strng)]+new_strng1)
else:
strng+="1"
return(strng)
else:
strng+="1"
return(strng)