如何在不使用Python中的replace()函数的情况下替换字符串中句子中所有实例中的字母(例如ABC)?
这是我到目前为止所做的,但为了替换a、b和c,我想知道如何将替换句子中所有出现的3个字母合并到一起。我也不允许使用replace()函数如何在不使用Python中的replace()函数的情况下替换字符串中句子中所有实例中的字母(例如ABC)?,python,python-3.x,for-loop,Python,Python 3.x,For Loop,这是我到目前为止所做的,但为了替换a、b和c,我想知道如何将替换句子中所有出现的3个字母合并到一起。我也不允许使用replace()函数 def changeLetters(word): for letter in word: if letter == "a": #I would like to replace a,b and c word.replace(letter,"!") #replace the replace() function
def changeLetters(word):
for letter in word:
if letter == "a": #I would like to replace a,b and c
word.replace(letter,"!") #replace the replace() function
return word
用户输入示例:
Amy buys carrots and apples
用户输出示例:
!my 3uys 8!rrots !nd !pples
答复:
first_word = "Amy buys carrots and apples"
def changeLetters(word):
word_list = [] #creates a list to be filled by letters
for letter in word: # fills the list with letters from string
if letter == "a" or letter == "b" or letter == "c": #searches for a b or c
letter = "!" #replaces a b or c with !
word_list.append(letter) # appends the current letter to the list
new_word = "".join(word_list) #joins the letters in the list into a string
return new_word # returns the value of the new word
print(changeLetters(first_word))
您可以根据需要修改或插入“if”语句以替换大写字母“A”,或为字母指定不同的替换字符。答案:
first_word = "Amy buys carrots and apples"
def changeLetters(word):
word_list = [] #creates a list to be filled by letters
for letter in word: # fills the list with letters from string
if letter == "a" or letter == "b" or letter == "c": #searches for a b or c
letter = "!" #replaces a b or c with !
word_list.append(letter) # appends the current letter to the list
new_word = "".join(word_list) #joins the letters in the list into a string
return new_word # returns the value of the new word
print(changeLetters(first_word))
您可以修改或插入“if”语句以替换大写字母“A”,或根据需要为字母指定不同的替换字符。不清楚您要做什么。您说要替换
a
、b
和c
,但您的代码(未成功)尝试替换a
之外的每个字母。你能给出一个示例输出来配合示例输入吗?你可以通过覆盖它来“替换”字母。请记住,您可以索引字符串,即如果a=“cat”
,那么a[0]
将是c
,a[1]
将是a
等。您可以通过执行a[1]=“*”
来使用它,这将使c*t
。请,发布您想要的结果。@AriCooper Davis是的,但是如果这个词是用户输入的呢?如果输入被分配给执行函数的变量,我下面的解决方案在这种情况下会起作用。不清楚您想做什么。您说要替换a
、b
和c
,但您的代码(未成功)尝试替换a
之外的每个字母。你能给出一个示例输出来配合示例输入吗?你可以通过覆盖它来“替换”字母。请记住,您可以索引字符串,即如果a=“cat”
,那么a[0]
将是c
,a[1]
将是a
等。您可以通过执行a[1]=“*”
来使用它,这将使c*t
。请,发布您想要的结果。@AriCooper Davis是的,但是如果这个词是用户输入的呢?如果输入被分配给执行函数的变量,我下面的解决方案在这种情况下会起作用。谢谢!然而,如果你想用3代替b,用8代替c,那该怎么办呢!替换所有a、b和c“”。加入(['3'如果x=='b'否则'8'如果x=='c'否则x代表word中的x])
谢谢!然而,如果你想用3代替b,用8代替c,那该怎么办呢!替换所有a、b和c''。连接(['3'如果x=='b'否则'8'如果x=='c'否则x代表word中的x])