Need help getting specific character through user input - python

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"))

Related

Very Beginner Python: Replacing Part of a String

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.

How to change a single letter in input string

I'm newbie in Python so that I have a question. I want to change letter in word if the first letter appears more than once. Moreover I want to use input to get the word from user. I'll present the problem using an example:
word = 'restart'
After changes the word should be like this:
word = 'resta$t'
I was trying couple of ideas but always I got stuck. Is there any simple sollutions for this?
Thanks in advance.
EDIT: In response to Simas Joneliunas
It's not my homework. I'm just finished reading some basic Python tutorials and I found some questions that I couldn't solve on my own. My first thought was to separate word into a single letters and then to find out the place of the letter I want to replace by "$". I have wrote that code but I couldn't came up with sollution how to get to specific place and replace it.
word = 'restart'
how_many = {}
for x in word:
how_many=+1
else:
how_many=1
for y in how_many:
if how_many[y] > 0:
print(y,how_many[y])
Using str.replace:
s = "restart"
new_s = s[0] + s[1:].replace(s[0], "$")
Output:
'resta$t'
Try:
"".join([["$" if ch in word[:i] else ch for i, ch in enumerate(word)])
enumerate iterates through the string (i.e. a list of characters) and keeps a running index of the iteration
word[:i] checks the list of chars until the current index, i.e. previously appeared characters
"$" if ch in word[:i] else ch means replace the character at existing position with $ if it appears before others keep the character
"".join() joins the list of characters into a single string.
This is where the python console is handy and lets you experiment. Since you have to keep track of number of letters, for a good visual I would list the alphabet in a list. Then in the loop remove from the list the current letter. If letter does not exist in the list replace the letter with $.
So check if it exists first thing in the loop, if it exists, remove it, if it doesn’t exist replace it from example above.

How do I reference a different character in a string while iterating through the string in Python?

I'm trying to write a script that can take doubled letters (aa or tt, for instance) and change them to that letter followed by ː, the length symbol (aa would become aː, and tt would become tː). I want to do this by iterating through the string, and replacing any character in the string that's the same as the last one with a ː. How do I do that?
You could try something like this. I iterated through string and checked each letter against the previous letter. If they match it performs the replacement if not it moves on and stores the new previous letter in previousletter. Also I used the .lower() method to mactch letters even if one is capitalized and one is not.
string = "Tthis is a testt of the ddouble letters"
previousletter = string[0]
for letter in string:
if letter.lower() == previousletter.lower():
string = string.replace("%s%s" % (previousletter, letter) , "%s:" % (letter))
previousletter = letter
print(string)
And here is the output:
t:his is a test: of the d:ouble let:ers
I hope this helps and feel free to ask any questions on the code that I used. Happy programming!

Method of slicing strings starting at the first blank space

I believe my professor taught us a way to begin parsing through a string at the first occurrence of a blank space (or any character for that matter) but I seem to have forgotten it. I'm trying to slice through a sentence starting at the first letter of the second word. Can anyone give me some help?
The code would receive a string similar to that shown below:
'Donald Springman 50 98.0\nKenneth Clarke 52 97.3\nRon Martin 51 95.5'
What I need to do is sort the strings by the given last names. So what I am hoping for is a way to simply bypass the first word in the string, and start parsing at the first space, therefore starting at the second word.
If I understand what you mean is:
string = 'word1 word2 word3'
print(string[string.find(' ') + 1:])
outputs:
'word2 word3'

Procedure in Python

Question
Write a procedure that takes a string of words separated by spaces (assume no punctuation or capitalization), together with a ”target” word, and shows the position of the target word in the string of words. For example, if the string is:
'we dont need no education we dont need no thought control no we dont'
and the target is the word ”dont” then your procedure should return the list 1, 6, 13 because ”dont” appears at the 1st, 6th, and 13th position in the string. (We start counting positions of words in the string from 0.) Your procedure should return False if the target word doesn’t appear in the string.
My solution-
def procedure(string,target):
words=string.split(" ") #turn the string into a list of words
solution=[] #list that will be displayed
for i in range(len(words)):
if words[i]==target: solution.append(i)
if len(solution)==0: return False
return solution
string="we dont need no education we dont need no thought control no we dont"
print procedure(string, "dont")
assert procedure(string, "dont")
Why is this not running in python?! The problem is on print procedure(string, "dont") it mentions invalid syntax. I am running it in the IDLE.
The following is your code with the indentation fixed, compare this with what you posted and you should see why it now works.
It is unclear to me why your original code has a problem because the indentation controls how python views the blocks of code and will fail to run if the indentation is incorrect. I suspect that your problem is that you had these lines in your code:
for i in range(len(words)):
if words[i]==target: solution.append(i)
if len(solution)==0: return False
The above will fail and return False because solution length will be 0 on the first iteration if your word is not found on the first iteration, you should check the len of solution outside the scope of the for loop.
In [42]:
def procedure(string,target):
words=string.split(" ") #turn the string into a list of words
solution=[] #list that will be displayed
for i in range(len(words)):
if words[i]==target: solution.append(i)
if len(solution)==0: return False
return solution
string="we dont need no education we dont need no thought control no we dont"
print(procedure(string, "dont"))
assert(procedure(string, "dont"))
[1, 6, 13]
You can user a list comprehension for this:
def list_word_indexes(word, text):
return [index for index, text_word in enumerate(text.split())
if text_word == word]
The problem is on print procedure(string, "dont") it mentions invalid syntax
This means you are using python 3, where print is a function and not a statement. You should add brackets around the argument(s) to print or make sure to use python 2.
eg.
print(procedure(string, "dont"))

Categories

Resources