Python: Remove words from a given string - python

I'm quite new to programming (and this is my first post to stackoverflow) however am finding this problem quite difficult. I am supposed to remove a given string in this case (WUB) and replace it with a space. For example: song_decoder(WUBWUBAWUBWUBWUBBWUBC) would give the output: A B C. From other questions on this forums I was able to establish that I need to replace "WUB" and to remove whitespace use a split/join. Here is my code:
def song_decoder(song):
song.replace("WUB", " ")
return " ".join(song.split())
I am not sure where I am going wrong with this as I the error of WUB should be replaced by 1 space: 'AWUBBWUBC' should equal 'A B C' after running the code. Any help or pointing me in the right direction would be appreciated.

You're close! str.replace() does not work "in-place"; it returns a new string that has had the requested replacement performed on it.
Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.
Do this instead:
def song_decoder(song):
song = song.replace("WUB", " ")
return " ".join(song.split())
For example:
In [14]: song_decoder("BWUBWUBFF")
Out[14]: 'B FF'

Strings are immutable in Python. So changing a string (like you try to do with the "replace" function) does not change your variable "song". It rather creates a new string which you immediately throw away by not assigning it to something. You could do
def song_decoder(song):
result = song.replace("WUB", " ") # replace "WUB" with " "
result = result.split() # split string at whitespaces producing a list
result = " ".join(result) # create string by concatenating list elements around " "s
return result
or, to make it shorter (one could also call it less readable) you can
def song_decoder(song):
return " ".join(song.replace("WUB", " ").split())

Do the both steps in a single line.
def song_decoder(song):
return ' '.join(song.replace('WUB',' ').split())
Result
In [95]: song_decoder("WUBWUBAWUBWUBWUBBWUBC")
Out[95]: 'A B C'

Related

How to return an ordered string from an unordered one?

I am trying to solve a problem but struggling with the logic approach to it. The problem is as follows:
"Your task is to sort a given string. Each word in the string will contain a single number. This number is the position the word should have in the result.
Note: Numbers can be from 1 to 9. So 1 will be the first word (not 0).
If the input string is empty, return an empty string. The words in the input String will only contain valid consecutive numbers."
For e.g. "is2 Thi1s T4est 3a" --> "Thi1s is2 3a T4est"
I have tried the following so far:
def order(sentence):
my_string = "is2 Thi1s T4est 3a"
new_string = " "
for i in my_string:
if i in my_string == none
return new_string = " "
else:
if i in my_string
return new_string
But stuck on continuing the next bit. How can I put "put words into order starting from 1" into python code into my for loop?
I'm a beginner in python and programming so I am not entirely sure if the approach I'm making is the best logical way to do so, by creating an empty string new_string and then sorting my_string into that. Is this a good way of approaching this? I am stuck on which direction to go after this.
you could do :
r = "is2 Thi1s T4est 3a"
def get_number(w) :
for x in w :
try :
i = int(x)
return i
except :
pass
return None
ordered_list = " ".join((sorted( s.split(' ') , key = get_number)))
the function get_number allows to get the first number appearing in a word, so we split the sentence to get the words it's made of , r.split(' ') gives ['is2', 'Thi1s', 'T4est', '3a'], we order then the list using ordered builtin function , it takes a list and a function that yields the keys over which we want to order the list, and outputs the ordered list, we then use the builtin function join to join the list using a space separator.
Output :
Out[425]: 'Thi1s is2 3a T4est'

Python - Print Each Sentence On New Line

Per the subject, I'm trying to print each sentence in a string on a new line. With the current code and output shown below, what's the syntax to return "Correct Output" shown below?
Code
sentence = 'I am sorry Dave. I cannot let you do that.'
def format_sentence(sentence):
sentenceSplit = sentence.split(".")
for s in sentenceSplit:
print s + "."
Output
I am sorry Dave.
I cannot let you do that.
.
None
Correct Output
I am sorry Dave.
I cannot let you do that.
You can do this :
def format_sentence(sentence) :
sentenceSplit = filter(None, sentence.split("."))
for s in sentenceSplit :
print s.strip() + "."
There are some issues with your implementation. First, as Jarvis points out in his answer, if your delimiter is the first or last character in your string or if two delimiter characters are right next to each other, None will be inserted into your array. To fix this, you need to filter out the None values. Also, instead of using the + operator, use formatting instead.
def format_sentence(sentences):
sentences_split = filter(None, sentences.split('.'))
for s in sentences_split:
print '{0}.'.format(s.strip())
You can split the string by ". " instead of ".", then print each line with an additional "." until the last one, which will have a "." already.
def format_sentence(sentence):
sentenceSplit = sentence.split(". ")
for s in sentenceSplit[:-1]:
print s + "."
print sentenceSplit[-1]
Try:
def format_sentence(sentence):
print(sentence.replace('. ', '.\n'))

a mistake I keep having with for loops and return statements

I have been noticing a problem I am having whenever I try to make a function that takes changes a string or a list then returns it.
I will give you an example of this happening with a code I just wrote:
def remove_exclamation(string):
string.split(' ')
for i in string:
i.split()
for char in i:
if char == '!':
del char
''.join(i)
' '.join(string)
return string
For instance, I create this code to take a string as its parameter, remove any exclamation in it, the return it changed. The input and output should look like this:
>>>remove_exclamation('This is an example!')
'This is an example'
But instead I get this:
>>>remove_exclamation('This is an example!')
'This is an example!'
The function is not removing the exclamation in the output, and is not doing what I intended for it to day.
How can I keep avoiding this when I make for loops, nested for loops etc?
You write your code and formulate your question as if it was possible to modify strings in Python. It is not possible.
Strings are immutable. All functions which operate on strings return new strings. They do not modify existing strings.
This returns a list of strings, but you are not using the result:
string.split(' ')
This also:
i.split()
This deletes the variable named char. It does not affect the char itself:
del char
This creates a new string which you do not use:
''.join(i)
This also:
' '.join(string)
All in all, almost every line of the code is wrong.
You probably wanted to do this:
def remove_exclamation(string):
words = string.split(' ')
rtn_words = []
for word in words:
word_without_exclamation = ''.join(ch for ch in word if ch != '!')
rtn_words.append(word_without_exclamation)
return ' '.join(rtn_words)
But in the end, this does the same thing:
def remove_exclamation(string):
return string.replace('!', '')
Without clearly knowing the intentions of your function and what you are attempting to do. I have an alternative to the answer that zvone gave.
This option is to remove any characters that you have not defined in an allowed characters list:
characters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ "
test_string = "This is an example!"
test_string = ''.join(list(filter(lambda x: x in characters, test_string)))
print(test_string)
This outputs:
This is an example
Note, this is the Python 3 version.
Python 2, you do not need the ''.join(list())
Doing it this way would allow you to define any character that you do not want present in your string, and it will remove them.
You can even do the reverse:
ignore_characters= "!"
test_string = "This is an example!"
test_string = ''.join(list(filter(lambda x: x not in ignore_characters, test_string)))
print(test_string)
Strings are immutable in Python. And you cannot change them. You can however, re-assign there values.
That is where your problem lies. You never reassign the value of your strings, when you call .split() on them.
But there are also others errors in your program such as:
Your indention
The fact that your just returning the string thats passed into the function
Your use of the del statement
etc.
Instead, create a new string by iterating through the old one and filtering out the character(s) you do not want, via list comprehension and ''.join().
def remove_exclamation(string):
return ''.join([char for char in string if char != '!'])
But as #Moses has already said in the comments, why not just use str.replace()?:
string = string.replace('!', '')
def remove_exclamation(string):
#you think you are splitting string into tokens
#but you are not assigning the split anywhere...
string.split(' ')
#and here you are cycling through individual _chars_ in string which was not affected by the split above ;-)
for i in string:
#and now you are splitting a 1-char string and again not assigning it.
i.split()
And string is still your input param, which I assume is of type str. And immutable.
On top of which, if you were import/using the string module, you would be shadowing it
A big part of your confusion is knowing when the methods mutate the objects and when they return a new object. In the case of strings, they never mutate, you need to assign the results to a new variable.
On a list however, and the join() somewhere makes me think you want to use a list, then methods generally change the object in place.
Anyway, on to your question:
def remove_exclamation(inputstring, to_remove="!"):
return "".join([c for c in inputstring if c != to_remove])
print (remove_exclamation('This is an example!'))
output:
This is an example

Punctuation Replacement Python

Learning python and can't seem to figure out why my code doesn't work, I'm trying to replace all punctuation in a given string with a space. Here's my code...
import string
def replace(text):
for char in text:
if char in string.punctuation:
text.replace(char, " ")
return text
test = "Ok! Where, to now?"
#expected "Ok Where to now "
#returned "Ok! Where to now?"
Any input is appreciated! Thanks!
replace doesn't modify the string passed into the first argument (string objects are immutable, meaning the object itself can't be modified). So you'll need to update the text variable with the return value of the replace operation yourself:
text = text.replace(char, " ")
From the documentation (emphasis mine):
Return a copy of string s with all occurrences of substring old replaced by new. If the optional argument maxreplace is given, the first maxreplace occurrences are replaced.
As a note about efficiency, python will create a new copy of the entire string every time text.replace is called. A better option is to convert thing string to a list of characters and then modify the list in place.
char_list = list(txt)
for i, char in enumerate(char_list):
if char in string.punctuation:
char_list[i] = " "
return "".join(char_list)
Better still would be to use the string modules translate function:
import string
x = 'this.! is my ^$input string?'
trans_tab = string.maketrans(string.punctuation, ' ' * len(string.punctuation))
print string.translate(x, trans_tab)
print x
print string.translate(x, None, string.punctuation)
Output:
this is my input string
this.! is my ^$input string?
this is my input string
Note that the translate function makes a copy and does not modify your original string.

Ways to slice a string?

I have a string, example:
s = "this is a string, a"
Where a ',' (comma) will always be the 3rd to the last character, aka s[-3].
I am thinking of ways to remove the ',' but can only think of converting the string into a list, deleting it, and converting it back to a string. This however seems a bit too much for simple task.
How can I accomplish this in a simpler way?
Normally, you would just do:
s = s[:-3] + s[-2:]
The s[:-3] gives you a string up to, but not including, the comma you want removed ("this is a string") and the s[-2:] gives you another string starting one character beyond that comma (" a").
Then, joining the two strings together gives you what you were after ("this is a string a").
A couple of variants, using the "delete the last comma" rather than "delete third last character" are:
s[::-1].replace(",","",1)[::-1]
or
''.join(s.rsplit(",", 1))
But these are pretty ugly. Slightly better is:
a, _, b = s.rpartition(",")
s = a + b
This may be the best approach if you don't know the comma's position (except for last comma in string) and effectively need a "replace from right". However Anurag's answer is more pythonic for the "delete third last character".
Python strings are immutable. This means that you must create at least 1 new string in order to remove the comma, as opposed to editing the string in place in a language like C.
For deleting every ',' character in the text, you can try
s = s.split(',')
>> ["this is a string", " a"]
s = "".join(s)
>> "this is a string a"
Or in one line:
s0 = "".join(s.split(','))
The best simple way is : You can use replace function as :-
>>> s = 'this is a string, a'
>>> s = s.replace(',','')
>>> s
'this is a string a'
Here, replace() function search the character ',' and replace it by '' i.e. empty character
Note that , the replace() function defaults all ',' but if you want only replace some ',' in some case you can use : s.replace(',' , '', 1)
To slice a string of arbitrary length into multiple equal length slices of arbitrary length you could do
def slicer(string, slice_length):
return [string[i:i + slice_length]
for i in xrange(0, len(string), slice_length)]
If slice_length does not divide exactly into len(string) then there will be a single slice at the end of the list that holds the remainder.

Categories

Resources