Python|删除除字母和数字以外的所有字符
给定一个字符串,任务是删除除数字和字母之外的所有字符。
字符串操作是日常编码和 Web 开发中一项非常重要的任务。 HTTP 查询中的大多数请求和响应都是字符串形式,有时我们需要删除一些无用的数据。让我们讨论一些 Pythonic 方法来删除除数字和字母之外的所有字符。
方法#1:使用re.sub
# Python code to demonstrate
# to remove all the characters
# except numbers and alphabets
import re
# initialising string
ini_string = "123abcjw:, .@! eiw"
# printing initial string
print ("initial string : ", ini_string)
# function to demonstrate removal of characters
# which are not numbers and alphabets using re
result = re.sub('[\W_]+', '', ini_string)
# printing final string
print ("final string", result)
输出:
initial string : 123abcjw:, .@! eiw
final string 123abcjweiw
方法 #2:使用 isalpha() 和 isnumeric()
# Python code to demonstrate
# to remove all the characters
# except numbers and alphabets
import re
# initialising string
ini_string = "123abcjw:, .@! eiw"
# printing initial string
print ("initial string : ", ini_string)
# function to demonstrate removal of characters
# which are not numbers and alphabets using re
getVals = list([val for val in ini_string
if val.isalpha() or val.isnumeric()])
result = "".join(getVals)
# printing final string
print ("final string", result)
输出:
initial string : 123abcjw:, .@! eiw
final string 123abcjweiw
方法 #3:使用alnum()
# Python code to demonstrate
# to remove all the characters
# except numbers and alphabets
# initialising string
ini_string = "123abcjw:, .@! eiw"
# printing initial string
print ("initial string : ", ini_string)
# function to demonstrate removal of characters
# which are not numbers and alphabets using re
getVals = list([val for val in ini_string if val.isalnum()])
result = "".join(getVals)
# printing final string
print ("final string", result)
输出:
initial string : 123abcjw:, .@! eiw
final string 123abcjweiw