I want to know how you can replace one letter of a string without replacing the same letter. For example, let the variable:
action = play sports.
I could substitute "play" for "playing" by doing print(action.replace("play", "playing")
But what if you have to of the same letters?
For example, what if you want to replace the last half of "honeyhoney" into "honeysweet" (Replacing the last half of the string to sweet?
Sorry for the bad wording, I am new to coding and really unfamiliar with this. Thanks!
def replaceLast(str, old, new):
return str[::-1].replace(old[::-1],new[::-1], 1)[::-1]
print(replaceLast("honeyhoney", "honey", "sweet"))
output
honeysweet
so the idea is to reverse the string and the old and new substrings,
so the last substring becomes the first, do a replace and then reverse the returned string once again, and the number 1 is to replace only once and not both matches
Another solution
def replaceLast(str, old, new):
ind = str.rfind(old)
if ind == -1 : return str
return str[:ind] + new + str[ind + len(old):];
print(replaceLast("honeyhoney", "honey", "sweet"))
output
honeysweet
so here we get the string from the beginning to the index of the last substring then we add the new substring and the rest of the string from where the old substring ends and return them as the new string, String.rfind returns -1 in case of no match found and we need to check aginst that to make sure the output is correct even if there is nothing to replace.
Related
I been trying to learn python a month and a half thu my uni course for my cs degree(1st year) so try to go a lil easy, i decided to redo from where i had problems
This is the question being asked
'''Given a string (someString) and an int (removeChar), create a new variable (newString)
where the char at index removeChar has been removed. Return newString.
Sounds simple but i cant wrap my head around outputting the newstring without the user inputted character
I know to use string slicing but i dont fully see how to use it with taking out the character and making the new string without it.
if i do
somestring = Alex
newstring = somestring[removechar:]
lets say the remove char is 2, the output is ex
however if i do
somestring = Alex
newstring = somestring[:removechar]
I get the output of Al
after that you would think okay so if removechar: is ex and :removechar is al then e is the letter thats changing the whole string.
But if i do [removechar:removechar] then it should take out the one letter but it doesnt nothing is in the output now. So i cant do it like that
I have to use string slicing for this question bc the time we would be doing this we wouldnt be able to use lists, replace, or translate
What am i missing here that you guys all see?
How this works is it gets all character(s) before the letter you want to remove and then because it is a string it adds that with all the character(s) after the letters you want to remove. The reason we add 1 is because if we do not it will include the letter you want to remove.
def remove(removeCharindx, string):
newString = string[:removeCharindx] + string[removeCharindx+1:]
return newString
print(remove(1, "Alex"))
I'm trying to make a short program that will find all the capital letters in a single string. I got it to work for the first two capital letters but it won't return the correct position of the last capital letter. What did I do wrong?
def capital_indexes(n):
listOfUpperPlaces = []
for x in n:
print(x)
if x.isupper():
characterPlace = n.index(x)
print(characterPlace)
listOfUpperPlaces.append(characterPlace)
return listOfUpperPlaces
print(capital_indexes("TEsTo"))
That is because n.index(x) returns the first occurrence of x in the string n. Because "T" occurs multiple times, n.index(x) returns the first occurrence of "T"
You want to iterate through range(len(n), like
def capital_indexes(n):
listOfUpperPlaces = []
for x in range(len(n)):
print(n[x])
if n[x].isupper():
print(x)
listOfUpperPlaces.append(x)
return listOfUpperPlaces
print(capital_indexes("TEsTo"))
The issue is the call to n.index(x)
This is searching the string to find x, and its able to find a capital T right at the beginning of the string.
A better way to do this would be to use enumerate, which gives you both the index and the item at the same time.
Can't code very well from a phone, but something like:
for index, character in enumerate(n):
if character.isUpper():
list_of_upper_places.append(index)
This will handle duplicates correctly, and will also be faster, since you don't need to search through the string just to count which character you are currently checking. It will be easier to read for most python programmers too.
So I'm trying to understand this solution for this problem. The goal here is to get the length of the longest substring from a string without having repeated characters.
How I understand it is that it goes character by character. Using the current index, it will subtract from the start position which is 0 because the the index initially starts 0. The addition of 1 is to compensate from starting at index 0.
If it encounters a duplicate character, it will shift the start position until no duplicates are found, this essentially separates the previous characters into a substring and starts at the position of the new substring with the duplicates, e.g. abcab => "abc" and "ab". It will continue until the length longest substring with no duplicates is found.
The code for the solution is as seen below:
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
used = {}
max_length = start = 0
for i,c in enumerate(s):
if c in used and start<=used[c]:
start = used[c]+1
else:
max_length = max(max_length,i-start+1)
used[c] = i
return max_length
What I don't understand is the start<=used[c] and used[c] = i part of this solution, what does it do? Can someone clarify with me?
EDIT: I understand that the dictionary is being used to keep track of the character count. I just don't understand the logic of it. Sorry, I should've clarified.
Thank you for reading.
If I understand correctly, your goal is to form a longest sub-string without repeating characters.
Algorithm Psuedocode:
Start with an empty string, with start as begin index of string. You want to extend the string until you get a duplicate character.
There are 2 possibilities for each character, either a character has been seen for the first time or character is already seen before. After each character we update bookmark used to keep track of last seen index.
a) If the character is not seen before, you can safely extend the current string.
Or
b) If the character was seen before, then we can only extend the string if it is not part of current string (start > used[c]). If it is part of the string ( start <= used[c]), you will need to update the sub-string's begin index start with index next to the last seen of current character as we don't want the characters to repeat, i.e. start = used[c] + 1. Since you are shortening the string in the latter case, maximal string won't be ending at this position.
"""
This code takes two strings and returns a copy of the first string with
all instances of the second string removed
"""
# This function removes the letter from the word in the event that the
# word has the letter in it
def remove_all_from_string(word, letter):
while letter in word:
find_word = word.find(letter)
word_length = len(word)
if find_word == -1:
continue
else:
word = word[:find_word] + word[find_word + word_length:]
return word
# This call of the function states the word and what letter will be
# removed from the word
print(remove_all_from_string("bananas", "an"))
This code is meant to remove a defined string from a larger define string. In this case the larger string is "bananas" and the smaller string which is removed is "an".
In this case the smaller string is removed multiple times. I believe I am very close to the solution of getting the correct output, but I need the code to output "bas". Instead, it outputs "ba".
The code is supposed to remove all instances of "an" and print whatever is left, however it does not do this. Any help is appreciated.
Your word_length should be len(letter), and as the while ensures the inclusion, don't need to test the value of find_word
def remove_all_from_string(word, replacement):
word_length = len(replacement)
while replacement in word:
find_word = word.find(replacement)
word = word[:find_word] + word[find_word + word_length:]
return word
Note that str.replace exists
def remove_all_from_string(word, replacement):
return word.replace(replacement, "")
You can simply use the .replace() function for python strings.
def remove_all_from_string(word, letter):
word = word.replace(letter, "")
return word
print(remove_all_from_string("bananas", "an"))
Output: bas
The Python language has built-in utilities to do that in a single expression.
The fact that you need to do that, indicates you are doing sme exercise to better understand coding, and that is important. (Hint: to do it in a single glob, just use the string replace method)
So, first thing - avoid using built-in tools that perform more than basic tasks - in this case, in your tentative code, you are using the string find method. It is powerful, but combining it to find and remove all occurrences of a sub-string is harder than doing so step by step.
So, what ou need is to have variables to annotate the state of your search, and your result. Variables are "free" - do not hesitate in creating as many, and updating then inside the proper if blocks to keep track of your solution.
In this case, you can start with a "position = 0", and increase this "0" until you are at the end of the parent string. You check the character at that position - if it does match the starting character of your substring, you update other variables indicating you are "inside a match", and start a new "position_at_substring" index - to track the "matchee". If at any point the character in the main string does not correspond to the character on the substring: not an occurrence, you bail out (and copy the skipped charactrs to your result -therefore you also have to accumulate all skipped characters in a "match_check" substring) .
Build your code with the simplest 'while', 'if' and variable updates - stick it all inside a function, so that whenever it works, you can reuse it at will with no effort, and you will have learned a lot.
How can I remove a letter from string in python.
For example, I have the word "study", I will have a list something like this "tudy","stdy","stuy","stud".
I have to use something like
for i in range(len(string)):
sublist.append(string0.replace(string[i], ""))
It works well. However, if I change the word "studys", when it replaces s with "", two s will disappear and It not works anymore (tudy instead study/tudys). I need help
Here's one:
s = 'studys'
lst = [s[:index] + s[index + 1:] for i in range(len(s))]
print(lst)
Output:
['tudys', 'sudys', 'stdys', 'stuys', 'studs', 'study']
Explanation:
Your code did not work because replace finds all the occurrences of the character in the word, and replaces them with the character you want. Now you can specify the number of counts to replace, as someone suggested in the comments, but even then replace checks the string from the beginning. So if you said, string.replace('s','',1) it will check the string from the start and as soon as it finds the first 's' it will replace it with '' and break, so you will not get the intended effect of removing the character at the current index.