How can I delete the letter in string - python

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.

Related

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

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

Ignore space in python

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 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.

Removing \n from myFile

I am trying to create a dictionary of list that the key is the anagrams and the value(list) contains all the possible words out of that anagrams.
So my dict should contain something like this
{'aaelnprt': ['parental', 'paternal', 'prenatal'], ailrv': ['rival']}
The possible words are inside a .txt file. Where every word is separated by a newline. Example
Sad
Dad
Fruit
Pizza
Which leads to a problem when I try to code it.
with open ("word_list.txt") as myFile:
for word in myFile:
if word[0] == "v": ##Interested in only word starting with "v"
word_sorted = ''.join(sorted(word)) ##Get the anagram
for keys in list(dictonary.keys()):
if keys == word_sorted: ##Heres the problem, it doesn't get inside here as theres extra characters in <word_sorted> possible "\n" due to the linebreak of myfi
print(word_sorted)
dictonary[word_sorted].append(word)
If every word in "word_list.txt" is followed by '\n' then you can just use slicing to get rid of the last char of the word.
word_sorted = ''.join(sorted(word[:-1]))
But if the last word in "word_list.txt" isn't followed by '\n', then you should use rstrip().
word_sorted = ''.join(sorted(word.rstrip()))
The slice method is slightly more efficient, but for this application I doubt you'll notice the difference, so you might as well just play safe & use rstrip().
Use rstrip(), it removes the \n character.
...
...
keys == word_sorted.rstrip()
...
You should try to use the .rstrip() function in your code, it will remove the "\n"
Here you can check it .rstrip()
strip only removes characters from the beginning or end of a string.
Use rstrip() to remove \n character
Also you can use replace syntax, to replace newline with something else.
str2 = str.replace("\n", "")
So, I see a few problems here, how is anything getting into the dictionary, I see no assignments? Obviously you've only provided us a snippet, so maybe that's elsewhere.
You're also using a loop when you could be using in (it's more efficient, truly it is).
with open ("word_list.txt") as myFile:
for word in myFile:
if word[0] == "v": ##Interested in only word starting with "v"
word_sorted = ''.join(sorted(word.rstrip())) ##Get the anagram
if word_sorted in dictionary:
print(word_sorted)
dictionary[word_sorted].append(word)
else:
# The case where we don't find an anagram in our dict
dictionary[word_sorted] = [word,]

Remove the first character of a string

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

Categories

Resources