Substract any word from this string
mystr= str("Hello code hub")
I have a long string, which is basically a list like str="Hello code hub," (and other items)
I was wondering if I can add or subtract some items, in other programming languages I can easily do: str=str-"hub," and get str="lamp, mirror,Hello code hub" this doesnt work in python
CodePudding user response:
If you want to substract something from you string, then you should use method replace Here is the example:
s = "Hello, World!"
print(s.replace("World!", "Earth!")) # Hello, Earth!
The first argument is the string you want to remove, and the second one is the string that you want to add instead of first string. In your case where you want to "delete" the string, then you should take the second argument as an empty string. That is the example:
s = "Hello, World!"
print(s.replace("World!", "")) # Hello,
CodePudding user response:
as I understand you want to remove some word or sequence of characters from another STRING.
for that just replace the text with nothing.
Syntax
your_text.replace(old,new)
Code
your_text = "Hello code hub"
# replace word in string
str_new = your_text.replace('hub','')
)
print(str_new)
Output
'Hello code '
str.replace(old, new[, count])
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.
CodePudding user response:
mystr = "Hello code hub"
# split your sentence with whitespace and new_line(\n)
split_str = mystr.split()
# remove word what you want
split_str.remove('code')
# reconstruct a sentence
print(' '.join(split_str))
If you create a function, you can use it more easily.
def sub(_str, word):
_str = _str.split()
_str.remove(word)
return ' '.join(_str)
print(sub(mystr,'code'))