如何在Python中去除字符串中除数字外的所有字符?
在本文中,我们将了解如何在Python中去除字符串中除数字外的所有字符。
第一种方法是使用for循环中的if语句,并使用join()方法将它们连接起来。我们将使用for循环迭代字符串,然后使用if语句检查每个字符是否是数字,如果是数字,则继续下一个字符,否则将替换该字符。
要重复迭代序列,请使用for循环。此功能更类似于在其他面向对象编程语言中看到的迭代器方法,并且不太像在其他编程语言中找到的for关键字。for循环允许我们针对列表、元组、集合等的每个元素运行一系列指令。
示例
在下面的示例中,我们以字符串作为输入,并使用for循环和if语句去除除数字外的所有字符−
str1 = "W3lc0m3" print("The given string is:") print(str1) print("Removing all the characters except digits") print(''.join(i for i in str1 if i.isdigit()))
输出
上面示例的输出如下所示−
The given string is: W3lc0m3 Removing all the characters except digits 303
Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.
使用filter()和lambda()
第二种方法是使用filter()和lambda()。我们将使用lambda()函数迭代字符串,并使用filter()方法过滤掉非数字字符,然后打印只包含数字的输出字符串,去除所有其他字符。
示例
在下面的示例中,我们以字符串作为输入,并使用filter()和lambda()去除除数字外的所有字符,并打印结果字符串。−
str1 = "W3lc0m3" print("The given string is:") print(str1) print("Removing all the characters except digits") print(list(filter(lambda i: i.isdigit(), str1)))
输出
上面示例的输出如下所示−
The given string is: W3lc0m3 Removing all the characters except digits ['3', '0', '3']
使用正则表达式
第二种技术使用正则表达式。导入re库,如果尚未安装,请安装它以使用它。导入re库后,我们可以使用正则表达式“\D”。我们将在re.sub函数中使用术语“\D”来表示除数字以外的所有字符,并将非数字字符替换为空格。
示例
在下面的示例中,我们以字符串作为输入,并使用正则表达式去除除数字以外的所有字符,并打印结果字符串−
import re str1 = "W3lc0m3" print("The given string is:") print(str1) print("Removing all the characters except digits") print(re.sub("\D", "", str1))
输出
上面示例的输出如下所示−
The given string is: W3lc0m3 Removing all the characters except digits 303