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
Related
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])
I need this code to ignore (not replace) spaces. Basically, it should capitalise every second letter of the alphabet only.
def spaces(test_space):
text = (str.lower, str.upper)
return ''.join(text[i%2](x) for i, x in enumerate(test_space))
print(spaces('Ignore spaces and other characters'))
print(spaces('Ignore spaces and 3rd characters!'))
Output
iGnOrE SpAcEs aNd oThEr cHaRaCtErS
iGnOrE SpAcEs aNd 3Rd cHaRaCtErS
This sounds like homework, so I'm only going to give suggestions and resources not complete code:
One way to do this would be to:
Replace every space with 2 of some character that can't appear in your text. for example use "$$". This can easily be done via python's replace function. We replace a space with 2 characters because each space is "throwing off" the index by one (mod 2), so by replacing each space by two characters corrects the problem (since 2 (mod 2) = 0).
Capitalize every other character using your current program
Replace each occurrence of '$$' with a space.
Put the spaces back using the indexes you saved
Output: iGnOrE sPaCeS aNd 3rD cHaRaCtErS!
Alternatively, you could iterate through the string (using a loop), keeping a position counter, but use a regex to ignore all non-Alphabet characters in the counter. You could also probably accomplish this succinctly via a list comprehension, although it might be more confusing to read.
def spaces(test_space):
return " ".join(
[
"".join(
char.upper() if i % 2 == 1 else char.lower()
for i, char in enumerate(word)
)
for word in test_space.split()
]
)
outputs
iGnOrE sPaCeS aNd oThEr cHaRaCtErS
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.
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!
I would like to remove the first character of a string.
For example, my string starts with a : and I want to remove that only. There are several occurrences of : in the string that shouldn't be removed.
I am writing my code in Python.
python 2.x
s = ":dfa:sif:e"
print s[1:]
python 3.x
s = ":dfa:sif:e"
print(s[1:])
both prints
dfa:sif:e
Your problem seems unclear. You say you want to remove "a character from a certain position" then go on to say you want to remove a particular character.
If you only need to remove the first character you would do:
s = ":dfa:sif:e"
fixed = s[1:]
If you want to remove a character at a particular position, you would do:
s = ":dfa:sif:e"
fixed = s[0:pos]+s[pos+1:]
If you need to remove a particular character, say ':', the first time it is encountered in a string then you would do:
s = ":dfa:sif:e"
fixed = ''.join(s.split(':', 1))
Depending on the structure of the string, you can use lstrip:
str = str.lstrip(':')
But this would remove all colons at the beginning, i.e. if you have ::foo, the result would be foo. But this function is helpful if you also have strings that do not start with a colon and you don't want to remove the first character then.
Just do this:
r = "hello"
r = r[1:]
print(r) # ello
deleting a char:
def del_char(string, indexes):
'deletes all the indexes from the string and returns the new one'
return ''.join((char for idx, char in enumerate(string) if idx not in indexes))
it deletes all the chars that are in indexes; you can use it in your case with del_char(your_string, [0])