如何使用Python从字符串列表中删除所有数字?
列表数据结构包含不同数据类型的元素,例如整数、字符串或浮点数。一旦在方括号内定义了列表数据结构中的元素,它们就无法更改。可以删除在字符串值内定义的数字,并且稍后仅返回不带数字的字符串值。在本文中,将从列表数据结构中的每个字符串中删除数字,并提供了字符串操作技术。
从字符串列表中删除所有数字
从字符串中删除整数并涉及从简单操作到复杂功能的过程。字符串由字符组成,仅打印不包含整数的字符串需要一些复杂的过程。
方法
- 方法1−使用replace模块
-
方法2−使用re模块
-
方法3−使用isalpha()方法
方法1:使用replace模块从字符串列表中删除所有数字的Python程序
使用replace模块用空格替换声明的变量中的整数。
算法
- 步骤1 - 定义带有一个输入字符串参数的函数。
-
步骤2 - 使用列表推导式,用空格替换每个元素。
-
步骤3 - 将输入初始化为一个字符串变量,并将其与整数一起分配给string1变量。
-
步骤4 - 打印列表的输出,不包含整数。
示例
#defining the remove integer function with one argument
def removeinteger(stringlist):
return [a.replace('0', '').replace('1', '').replace('2', '').replace('3', '').replace('4', '').replace('5', ''). replace('6', ''). replace('7', ''). replace('8', ''). replace('9', '') for a in stringlist]
#initializing the list of strings
string1 = ['John53mass', '66elsa98Marvel', '300perfect04stay']
#the newlist holds the string after removing the integers
newlist = removeinteger(string1)
#Print the function
print("The list of string after integer removal:", newlist)
输出
The list of string after integer removal: ['Johnmass', 'elsaMarvel', 'perfectstay']
方法2:使用re模块从字符串列表中删除所有数字的Python程序
re模块用于从给定的字符串列表中删除所有整数,然后将所有数字替换为字符串。
算法
- 步骤1 - 输入变量声明为包含字符和数字的组合,例如John53mass。
-
步骤2 - 程序通过从字符串中仅删除该数字(53)来工作。
-
步骤3 - 定义一个名为removeinteger()的函数,该函数有一个参数,并导入re模块以使用一些内置函数。
-
步骤4 - 使用re模块中的re.sub()函数查找字符串,然后用整数值替换它们。
-
步骤5 - 创建一个新列表newlist来保存结果。
-
步骤6 - for循环将根据列表的长度迭代遍历列表。
-
步骤7 - 最后,打印输出结果。
示例
#importing the required module
import re
#function defined with one argument
def removeint(val):
return re.sub("\d+", "", val)
#initializing the list of strings with numbers inside string
string1 = ['John53mass', '66elsa98Marvel', '300perfect04stay']
#initializing the empty list
newlist = []
#for loop is used to iterate through the list along with the len function
for a in range(len(string1)):
newlist.append(removeint(string1[a]))
#returning the list after removing the integers
print("The list of string after integer removal:", newlist)
输出结果
The list of string after integer removal: ['Johnmass', 'elsaMarvel', 'perfectstay']
方法3:使用isalpha()方法从字符串列表中删除所有数字的Python程序
使用isalpha()方法从元素列表中删除整数后,将打印列表。
算法
- 步骤1 − 输入可以是任何字符串以及数字,输出打印出没有数字的结果。
-
步骤2 − 声明一个空列表并将其赋值给一个空变量。
-
步骤3 − 使用列表推导,我们可以根据给定列表的长度迭代元素。
-
步骤4 − 使用join函数附加字母,然后将其存储在空列表中。
-
步骤5 − 打印出不含数字的最终列表。
示例
#initializing the list data structure with string and integer elements along with integer values
string1 = ['John53mass', '66elsa98Marvel', '300perfect04stay']
#declaring an empty list
empty = []
#for loop is used to iterate through the list by ranging based on the length
for a in range(len(string1)):
empty.append(''.join(e for e in string1[a] if e.isalpha()))
#printing the list after removing the integers from the list
print("The list of string after integer removal:", empty)
输出
The list of string after integer removal: ['Johnmass', 'elsaMarvel', 'perfectstay']
结论
Python被广泛应用于机器学习和人工智能等众多技术中。这些方法帮助程序员使用模块和列表推导式从字符串列表中去除整数。数据处理是当前技术中最重要的部分之一,从声明的输入字符串中去除整数是其中一项基本功能。