简体   繁体   English

从 Python 中的字符串中删除字母

[英]Remove letters from string in Python

I need to define a function that takes two arguments (s1, s2) .我需要定义一个带有两个参数(s1, s2)的函数。 This function should remove the letters of s2 that are in s1 .此函数应删除s1s2字母。 For example removing the letters "motor" from "motorcycle" should result in "cycle" .例如,从"motorcycle"删除字母"motor" "motorcycle"应该会产生"cycle" I know how to do it for a specific letter of one string, but not from two strings.我知道如何处理一个字符串的特定字母,而不是两个字符串。

Do s2.replace(s1, '')s2.replace(s1, '')

>>> a = 'motor'
>>> a.replace('moto', '')
'r'

Strings in Python are immutable, so to change the vale of a do - Python 中的字符串是不可变的,因此要更改执行的值 -

>>> a =a.replace('moto', '')

Specifically for your problem专门针对您的问题

def replace_letters(x,y):
   return x.replace(y,'')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM