簡體   English   中英

嘗試從Python 3中的字符串中刪除字母

[英]Trying to remove a letter from a string in Python 3

我正在嘗試從Python 3中的字符串中刪除字符。以下是我的代碼:

#Function that removes a character from a string
def removeChar(character, string):
    new_string = string.replace(character, "")

print(removeChar("e", "Hello World"))

但是,該程序的輸出僅為None 我的代碼有什么問題?

好吧,如果一個函數不return任何東西,Python解釋器將讓它返回None 因此,您應該聲明:

def removeChar(character, string):
     return string.replace(character, "")

此外,您實際上並沒有從字符串中刪除字符 ,字符串是不可變的 ,而是創建了字符串的副本,與給定字符串相比,該字符丟失了。

您必須在自己的函數之后返回new_string ,如下所示:

def removeChar(character, string):
    new_string = string.replace(character, "")
    return new_string

print(removeChar("e", "Hello World"))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM