[英]How to substract two string in python
mystr=str("Hello 代碼集線器")
我有一個長字符串,基本上是一個類似 str="Hello code hub," 的列表(和其他項目)
我想知道是否可以添加或減去一些項目,在其他編程語言中我可以輕松做到:str=str-“hub”並獲取 str="lamp, mirror,Hello code hub" 這在 python 中不起作用
如果你想從你的字符串中減去一些東西,那么你應該使用方法replace這是示例:
s = "Hello, World!"
print(s.replace("World!", "Earth!")) # Hello, Earth!
第一個參數是要刪除的字符串,第二個參數是要添加的字符串,而不是第一個字符串。 在您想要“刪除”字符串的情況下,您應該將第二個參數作為空字符串。 就是這個例子:
s = "Hello, World!"
print(s.replace("World!", "")) # Hello,
據我了解,您想從另一個字符串中刪除一些單詞或字符序列。
為此,只需將文本替換為任何內容。
your_text.replace(old,new)
your_text = "Hello code hub"
# replace word in string
str_new = your_text.replace('hub','')
)
print(str_new)
'Hello code '
str.replace(old, new[, count])
返回字符串的副本,其中所有出現的 ZE83AED3DDF4667DEC0DAAAACB2BB3BE0BZ 舊的替換為新的。 如果給定了可選參數 count,則僅替換第一個 count 出現。
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))
如果您創建一個 function,您可以更輕松地使用它。
def sub(_str, word):
_str = _str.split()
_str.remove(word)
return ' '.join(_str)
print(sub(mystr,'code'))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.