Replacing part of a string using a For loop - python

I need to get a user to enter a sentence for an assignment. Using a for loop, I then need to replace all spaces with %20 in order to prep the string to be used as a URL. I cannot for the life of me figure it out.
sentence = str(input("Please enter sentence:"))
space = (" ")
for space in sentence:
space.replace(sentence, space, "%20", 500)
print(sentence)
This is what I have entered so far but it is completely wrong.

String in Python can't be modified. The replace() function returns a new string with all the replacements done. You need to assign this result somewhere. So you can do:
sentence = sentence.replace(" ", "%20")
If you want to do it with a loop, you need to build the result in another variable.
new_sentence = ""
for char in sentence:
if char == " ":
new_sentence += "%20"
else:
new_sentence += char
There's no point in using replace() in the loop.

Replace everything after the first line with print(sentence.replace(" ","%20"))
or, if you really must use a loop:
s = ''
for x in sentence:
if x == ' ':
s += "%20"
else:
s += x
print(s)

you've got a few problems here:
the variable space that you define before the loop is equal to " " but then you're using the same name for the for loop variable, which is going to iterate through the string the sentence string, in the loop, it's going to use the value defined by the loop.
You're giving the replace method too many arguments, it's a method of the string object so you don't need to pass it the large string to operate on Replace Method
You're using the replace method on the space string and not on the sentence string
Good way to do it in real life:
old = ' '
new = '%20'
sentence = str(input("Please enter sentence:"))
print(sentence.replace(old,new))
The way your teacher is probably after:
sentence = str(input("Please enter sentence:"))
old = ' '
new = '%20'
newSentence = ''
for letter in sentence:
if letter == ' ':
newSentence += new
else:
newSentence += letter
print(newSentence)

Related

how to extract a sentence from string in python using simple for loop?

str1 = "srbGIE JLWokvQeR DPhyItWhYolnz"
Like I want to extract I Love Python from this string. But I am not getting how to.
I tried to loop in str1 but not successful.
i = str1 .index("I")
for letter in range(i, len(mystery11)):
if letter != " ":
letter = letter+2
else:
letter = letter+3
print(mystery11[letter], end = "")
In your for loop letter is an integer. In the the first line of the loop you need to compare mystery[11] with " ":
if mystery11[letter] != " ":
You can use a dict here, and have char->freq mapping of the sentence in it and create a hash table.
After that you can simply iterate over the string and check if the character is present in the hash or not, and if it is present then check if its count is greater than 1 or not.
Don't know if this will solve all your problems, but you're running your loop over the indices of the string, This means that your variable letter is an integer not a char. Then, letter != " " is always true. To select the current letter you need to do string[letter]. For example,
if mystery11[letter] != " ":
...
Here's how I'd go about:
Understand the pattern of the input: words are separated by blank spaces and we should get every other letter after the first uppercase one.
Convert string into a list;
Find the first uppercase letter of each element and add one so we are indexing the next one;
Get every other char from each word;
Join the list back into a string;
Print :D
Here's the code:
def first_uppercase(str):
for i in range(0, len(str)):
if word[i].istitle():
return i
return -1
def decode_every_other(str, i):
return word[i::2]
str1 = "srbGIE JLWokvQeR DPhyItWhYolnz"
# 1
sentence = str1.split()
clean_sentence = []
for word in sentence:
# 2
start = first_uppercase(word) + 1
# 3
clean_sentence.append(decode_every_other(word, start))
# 4
clean_sentence = ' '.join(clean_sentence)
print("Input: " + str1)
print("Output: " + clean_sentence)
This is what I ended up with:
Input: srbGIE JLWokvQeR DPhyItWhYolnz
Output: I Love Python
I've added some links to the steps so you can read more if you want to.
def split(word):
return [char for char in word]
a = input("Enter the original string to match:- ")
b = input("Enter the string to lookup for:- ")
c = split(a)
d = split(b)
e = []
for i in c:
if i in d:
e.append(i)
if e == c:
final_string = "".join(e)
print("Congrats!! It's there and here it is:- ", final_string)
else:
print("Sorry, the string is not present there!!")

Why does str.capitalize() not work as I expect?

Please, let me know if I'm not providing enough information. The goal of the program is to capitalize the first letter of every sentence.
usr_str = input()
def fix_capitalization(usr_str):
list_of_sentences = usr_str.split(".")
list_of_sentences.pop() #remove last element: ""
new_str = ''
for sentence in list_of_sentences:
new_str += sentence.capitalize() + "."
return new_str
print(fix_capitalization(usr_str))
For instance, if I input "hi. hello. hey." I expect it to output "Hi. Hello. Hey." but instead, it outputs "Hi. hello. hey."
An alternative would be to build a list of strings then concatenate them:
def fix_capitalization(usr_str):
list_of_sentences = usr_str.split(".")
output = []
for sentence in list_of_sentences:
new_sentence = sentence.strip().capitalize()
# If empty, don't bother
if new_sentence:
output.append(new_sentence)
# Finally, join everything
return ". ".join(output) +"."
You've entered the sentences with spaces between them. Now when you split the list the list at the '.' character the spaces are still remaining. I checked what the elements in the list were when you split it and the result was this.
'''
['hi', ' hello', ' hey', '']
'''

Cleaning up a string without split/strip/built-in functions

My requirements
Use Python to create a function cleanstring(S) to "clean up" the spaces in a sentence S.
The sentence may have extra spaces at the front and/or at the end and/or between words.
The subroutine returns a new version of the sentence without the extra spaces.
That is, in the new string, the words should be the same but there should be no spaces at the start, only one space between each word and no spaces at the end.
This program is about you writing code to search through a string to find words and so you are not allowed to use the split function in Python.
You can solve this problem with the basic capabilities of the if and while statements and string operations of len and concatentation.
For example: if the input is: " Hello to the world !" then the output should be: "Hello to the world!"
Question
My program deletes more characters in the program than needed.
Input: " Hello World ! "
Output: "HellWorl"
How do I fix the error in my program?
def cleanupstring (S):
newstring = ["", 0]
j = 1
for i in range(len(S) - 1):
if S[i] != " " and S[i+1] != " ":
newstring[0] = newstring[0] + S[i]
else:
newstring[1] = newstring [1] + 1
return newstring
# main program
sentence = input("Enter a string: ")
outputList = cleanupstring(sentence)
print("A total of", outputList[1], "characters have been removed from your
string.")
print("The new string is:", outputList[0])
Welcome to Stackoverflow. When I started reading I though this was going to be a "please answer my homework" question, but you've actually made a pretty fair effort at solving the problem, so I'm happy to try and help (only you can say whether I actually do).
It's sometimes difficult when you are learning a new language to drop techniques that are much more appropriate in other languages. Doing it character by character you normally just use for c in s rather than incrementing index values like you would in C (though either approach works, index incrementation where not necessary is sometimes regarded as "unpythonic"). Your basic idea seems to be to detect a space followed by another space, otherwise copying characters from the input to the output.
The logic can be simplified by retaining the last character you sent to the output. If it's a space, don't send any more spaces. A loop at the front gets rid of any leading spaces, and since there can be at most one space at the end it can be eliminated easily if present.
I'm not sure why you use a list to keep your results in, as it makes the code much more difficult to understand. If you need to return multiple pieces of information it's much easier to compute them in individual variables and then construct the result in the return statement.
So one desirable modification would be to replace newstring[0] with, say, out_s and newstring[1] with, say count. That will make it a bit clearer what's going on. Then at the end return [out_s, count] if you really need a list. A tuple using return out_s, count would be more usual.
def cleanupstring (s):
out_s = ''
count = 0
last_out = ' '
for c in s:
if c != ' ' or last_out != ' ':
last_out = c
out_s += c
else:
count += 1
if last_out == ' ':
count -= 1
out_s = out_s[:-1]
return out_s, count
# main program
sentence = input("Enter a string: ")
outputList = cleanupstring(sentence)
print("A total of", outputList[1], "characters have been removed from your string.")
print("The new string is:", outputList[0])
Sometimes you just don't have certain pieces of information that would help you to answer the question extremely succinctly. You most likely haven't yet been taught about the strip and replace methods, and so I imagine the following (untested) code
def cleanupstring(s):
out_s = s
while ' ' in out_s:
out_s = out_s.strip().replace(' ', ' ')
return out_s, len(s)-len(out_s)
would be right out.
Also, you can use an "unpacking assignment" to bind the different elements of the function's output directly to names by writing
s, c = cleanupstring(...)
I'm sure you will agree that
print("A total of", c, "characters have been removed from your string.")
print("The new string is:", s)
is rather easier to read. Python values readability so highly because with readable code it's easier to understand the intent of the author. If your code is hard to understand there's a good chance you still have some refactoring to do!
If the "space" it's literally spaces rather than whitespace then the following would work:
import re
def clean_string(value):
return re.sub('[ ]{2,}', ' ', value.strip())
If the stripped values contains consecutive spaces then replace with one space.
My approach would be to keep the last character available and make the decision whether it is a space or not:
def cleanupstring (S):
newstring = ["", 0]
last_character = ' ' # catch initial spaces
for i in range(len(S)-1):
char = S[i]
if char is ' ' and last_character is ' ':
continue # ignore
else:
last_character = char
newstring [0] = newstring[0] + char
return newstring

Python:Taking the first character without Lists

My code is about creating a password using the first character/digit of every word/number as a character in a sentence/phrase and printing it just as so.
Example: Stop and smell the 350 "roses". -> Sast3r. (Ignoring
quotations using r instead)
This would be very easy using lists, but you cannot use them in this assignment for my code. So, I don't know what to do now after what I have done so far
Function:
def create_password(phrase):
q = "'" # quotations
dq = '"' # double quotes
password = phrase[0]
for i in phrase:
x = phrase.find(" ")
if i.isalnum:
password += phrase[x + 1]
elif x == q or x == dq:
password += phrase[x + 2]
return password
Main:
# Imports
from credentials import create_password
# Inputs
phrase = str(input("Enter a sentence or phrase: "))
# Outputs
password = create_password(phrase)
print(password)
I think it is more straightforward to walk through the entire phrase without worrying about splitting on spaces. Instead keep track of whether or not you've just seen a space. You only want to add the character after just seeing a space.
def create_password(phrase):
q = "'" # quotations
dq = '"' # double quotes
#Initialize the password to be an empty string
password = ""
#We are at the start of a new word (want to add first index to password)
new_word = True
#Walk through every character in the phrase
for char in phrase:
#We only want to add char to password if the following is all true:
#(1) It's a letter or number
#(2) It's at the start of a new word
#(3) It's not a single quote
#(4) It's not a double quote
if char.isalnum and new_word:
if char != q and char != dq:
password += char
new_word = False #<-- After adding char, we are not at a new word
#If we see a space then we are going to be at a new word
elif char == " ":
new_word = True
return password
p = create_password('Stop and smell the 350 "roses"')
print(p)
Output:
Sast3r
You're definitely on the right track! Using the str.find() method is definitely the way to go!
However, you need to understand what the str.find() method does. Look at the signature:
str.find(sub [,start [,end) -> int
# sub -> character to find
# start -> where the function should start looking in the string
# end -> where the function should stop looking
# Returns a number, which is the place it found the character.
# If it didn't find anything, then return -1.
Without telling the function where to start, it will always find the first occurrence of the character in the string. It won't know that you're going through each character of the string.
So let's change it up a little bit:
for char_index in xrange(len(phrase)):
# Tell the method to look after char_index: we've already looked before this!
x = phrase.find(' ', char_index) index
if phrase[x+1].isalnum(): # It's a function, notice the brackets?
password += phrase[x + 1]
elif phrase[x+2] == q or phrase[x+2] == dq:
password += phrase[x + 2]
Hopefully, this should get your desired password.
Give priority to the use of built-in function, for example, every time you find the location of space, then why not directly in accordance with the space for spilt function, so that the string directly to the character list, each element is a word, and then remove each element in the list.
def create_password(phrase):
password = ''
phrase_list = phrase.split(' ')
print (phrase_list)
for i in phrase_list:
print (i[0])
password += i[0]
return password
if __name__ == '__main__':
# Inputs
phrase = str(input("Enter a sentence or phrase: "))
# Outputs
password = create_password(phrase)
print(password)
Try taking the first character in the string, and then every character that follows a space. It looks like you have the right idea.

using a while True loop

Problem 1.
This problem provides practice using a while True loop. Write a function named
twoWords that gets and returns two words from a user. The first word is of a
specified length, and the second word begins with a specified letter.
The function twoWords takes two parameters:
an integer, length, that is the length of the first word and
a character, firstLetter, that is the first letter of the second word.
The second word may begin with either an upper or lower case instance of
firstLetter. The function twoWords should return the two words in a list. Use
a while True loop and a break statement in the implementation of twoWords. The
following is an example of the execution of twoWords:
print(twoWords(4, 'B')):
A 4-letter word please two
A 4-letter word please one
A 4-letter word please four
A word beginning with B please apple
A word beginning with B please pear
A word beginning with B please banana
['four', 'banana']
This is what I have so far, but it keeps asking me the first question over again
even if I have the right word length. What am I doing wrong?
def twoWords(length, firstLetter):
wordLen = input('A 4-letter word please ')
while len(wordLen) != int(length):
wordlen = input('A 4-letter word please ')
word = input('A word beginning with ' + firstLetter + ' please ')
while word[0] != firstLetter:
word = input('A word beginning with ' + firstLetter + ' please ')
return[wordLen, word]
def twoWords(length,firstLetter):
firstWord = ""
secondWord= ""
while True:
firstWord = input('A ' + str(length) + '-letter word please.')
if length == len(firstWord):
break
while True:
secondWord = input('A word beginning with ' + firstLetter+ ' please')
if secondWord[0] == firstLetter.upper() or secondWord[0] == firstLetter.lower():
break
return [firstWord,secondWord]
print(twoWords(4,'B'))
def twoWord(length, firstLetter):
while True:
word1=(input("Enter a "+ str(length)+"-letter word please:"))
if len(word1)==int(length):
break
while True:
word2=input("Please enter the word beginning with "+firstLetter+" please:")
if word2[0].upper()==firstLetter or word2[0].lower()==firstLetter:
break
return word1, word2
print(twoWord(5, 'b'))

Categories