How to remove the first and last letter of a string? - python

I'd like to remove the first and last letter from a string. So far I've made something like this:
string = "wildcatatewonderfulcake"
first_letter_remvoer = string.strip(string[0])
print(first_letter_remvoer)
second_letter_remover = first_letter_remvoer.strip(string[-1])
print(second_letter_remover)
But sadly if the first letter is for example 'c' and 'c' exists more then once in a given string, it deletes every single 'c' from the string. Same goes with the last letter.

Strip removes all instances of the letter from the start and end of a string until it encounters a character that isn't expected to be stripped, you can just slice
string[1:-1]
Otherwise you can use removesuffix/prefix
string.removesuffix(string[-1]).removeprefix(string[0])

Related

How can i convert specific characters in a string and in a specific index

For example i have the string "alba iuliara" and what i want to do is to convert all the "a" with "A" but not the first and the last "a". The result must be "albA iuliAra"
Any idea how can i do that using a statement like while, if and etc..
It's pretty easy if you use the replace method.
Code if you don't consider the first and last characters
your_string = "alba iuliara"
your_string = f"{your_string[0]}{your_string[1:-1].replace('a','A')}{your_string[-1]}"
print(your_string)
your_string = "Namaskara"
rep_char='a'
occ1=your_string.find(rep_char) #Searches for first occurence of replacing character
occn=your_string.rfind(rep_char) #Searches for last occurence of replacing character
#from startig poition of string to your first occurence of character and last occurence of character to end of the string nothing will be replaced. for remaining string character will be replaced with uppercase
your_string = f"{your_string[0:occ1+1]}{your_string[occ1+1:occn].replace(rep_char,rep_char.upper())}{your_string[occn:]}"
print(your_string)
output: NamAskAra
I have used #jock logic but modified to make it generic.

Why I am getting these different outputs?

print('xyxxyyzxxy'.lstrip('xyy'))
# output:zxxy
print("xyxefgooeeee".lstrip("efg"))
# ouput:xyxefgooeeee
print('reeeefooeeee'.lstrip('eeee'))
# output:reeeefooeeee
Here for the last two print statements, I am expecting output as a first print statement, as it has stripped 'xyxxyy', but in the last two print statements, it is not stripping in the same way as it has done in first. Please tell me why it so?
In Python leading characters in Strings containing xyy are removed because of .lstrip(). For example:
txt = ",,,,,ssaaww.....banana"
x = txt.lstrip(",.asw")
print(x)
The output will be: banana
string.lstrip(chars) removes characters from the left size of the string until it reached a character that does not appear in chars.
In your second and third examples, the first character of the string does not appear in chars, so no characters are removed from the string.
I just got to know lstrip() removes, all combinations of the characters passed as an argument are removed from the left-hand side.
I think because the order of char doesn't matter.
xyy or yxx will result in the same thing. It will remove chars from the left side until it sees a char that is not included. For example:
print('xyxxyyzxxy'.lstrip('xyy'))
zxxy
print('xyxxyyzxxy'.lstrip('yxx'))
zxxy
In fact, if you only used 2 chars 'xy' or 'yx' you will get the same thing:
print('xyxxyyzxxy'.lstrip('xy'))
zxxy
In the other cases, the first left char is not included, therefore there's no stripping
lstring using the set of the chars in the string and then removes the all characters from the primary string start from the left
print('xyxefgooeeee'.lstrip('yxefg'))
"""In 'xyxefgooeeee' the first char is 'x' and it exists in the 'yxefg' so
will be removed and then it will move to the next char 'y','x','x','e','f',
'g' and then 'o' which doesn't exist. therefore will return string after 'o'
"""
OutPut : ooeeee
print('xyxefgooeeee'.lstrip('efg'))
"""In the xyxefgooeeee' the first char 'x' does to exist in the 'efg' so will
not be removed and will not move to the next char and will return the
entire primary string
"""
OutPut: xyxefgooeeee

How can I delete the letter in string

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.

Python - string index out of range issue

This is the question I was given to solve:
Create a program inputs a phrase (like a famous quotation) and prints all of the words that start with h-z.
I solved the problem, but the first two methods didn't work and I wanted to know why:
#1 string index out of range
quote = input("enter a 1 sentence quote, non-alpha separate words: ")
word = ""
for character in quote:
if character.isalpha():
word += character.upper()
else:
if word[0].lower() >= "h":
print(word)
word = ""
else:
word = ""
I get the IndexError: string index out of range message for any words after "g". Shouldn't the else statement catch it? I don't get why it doesn't, because if I remove the brackets [] from word[0], it works.
#2: last word not printing
quote = input("enter a 1 sentence quote, non-alpha separate words: ")
word = ""
for character in quote:
if character.isalpha():
word += character.upper()
else:
if word.lower() >= "h":
print(word)
word = ""
else:
word = ""
In this example, it works to a degree. It eliminates any words before 'h' and prints words after 'h', but for some reason doesn't print the last word. It doesn't matter what quote i use, it doesn't print the last word even if it's after 'h'. Why is that?
You're calling on word[0]. This accesses the first element of the iterable string word. If word is empty (that is, word == ""), there is no "first element" to access; thus you get an IndexError. If a "word" starts with a non-alphabetic character (e.g. a number or a dash), then this will happen.
The second error you're having, with your second code snippet leaving off the last word, is because of the approach you're using for this problem. It looks like you're trying to walk through the sentence you're given, character by character, and decide whether to print a word after having read through it (which you know because you hit a space character. But this leads to the issue with your second approach, which is that it doesn't print the last string. That's because the last character in your sentence isn't a space - it's just the last letter in the last word. So, your else loop is never executed.
I'd recommend using an entirely different approach, using the method string.split(). This method is built-in to python and will transform one string into a list of smaller strings, split across the character/substring you specify. So if I do
quote = "Hello this is a sentence"
words = quote.split(' ')
print(words)
you'll end up seeing this:
['Hello', 'this', 'is', 'a', 'sentence']
A couple of things to keep in mind on your next approach to this problem:
You need to account for empty words (like if I have two spaces in a row for some reason), and make sure they don't break the script.
You need to account for non-alphanumeric characters like numbers and dashes. You can either ignore them or handle them differently, but you have to have something in place.
You need to make sure that you handle the last word at some point, even if the sentence doesn't end in a space character.
Good luck!
Instead of what you're doing, you can Iterate over each word in the string and count how many of them begin in those letters. Read about the function str.split(), in the parameter you enter the divider, in this case ' ' since you want to count the words, and that returns a list of strings. Iterate over that in the loop and it should work.

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!

Categories

Resources