由于各种模块的可用性,Python是自然语言处理和文本分析中最常用的编程语言之一。我们在Python中使用字符串来分析文本数据。在Python中,单引号或双引号包围着每个字符串。然而,输入的字符串可能在中间包含引号。本文讨论了在Python中从字符串中去除引号的不同方法。
在Python中使用For循环去除字符串中的引号
在Python中,我们使用for循环来迭代一个可迭代的对象,如字符串或列表。为了使用 for 循环从一个字符串中去除引号,我们将使用以下步骤。
- 首先,我们将创建一个名为
quotes的列表来存储单引号和双引号字符。 - 然后,我们将创建一个名为
newStr的空字符串来存储输出字符串。 - 现在,我们将使用for循环来迭代输入字符串中的字符。
- 在迭代过程中,如果我们发现除单引号或双引号以外的字符,我们将使用字符串连接操作符将这些字符追加到
newStr。为了检查一个字符是单引号还是双引号,我们将使用成员运算符。 - 如果我们在字符串中发现一个单引号或双引号字符,我们将跳过它。
- 执行for循环后,我们将在变量
newStr中得到输出字符串。
你可以在下面的例子中观察整个过程。
input_string = "Pythonf'orb''eginn'er's"
print("The input string is:", input_string)
quotes = ["'", '"']
newStr = ""
for character in input_string:
if character not in quotes:
newStr += character
print("The output string is:", newStr)
输出。
The input string is: Pythonf'orb''eginn'er's
The output string is: Pythonforbeginners
我们可以直接比较字符串中是否存在单引号和双引号的字符,而不是使用名为quotes 的列表和成员操作符。为此,我们将在if语句中使用平等运算符来比较这些字符。其余的过程和上面一样。
input_string = "Pythonf'orb''eginn'er's"
print("The input string is:", input_string)
newStr = ""
for character in input_string:
if character == "'" or character == '"':
continue
else:
newStr += character
print("The output string is:", newStr)
输出。
The input string is: Pythonf'orb''eginn'er's
The output string is: Pythonforbeginners
在这里,你可以看到,我们没有使用列表和成员运算符。相反,我们在if语句中使用平等运算符直接比较了这些字符。
在 Python 中使用 filter() 函数和 join() 方法从一个字符串中去除引号
filter() 函数是用来从一个可迭代对象中排除元素的。filter()函数的语法如下。
filter(input_function,iterable_object)
这里。
iterable_object是我们需要从中排除元素的python对象。input_function是一个函数,它接收iterable_object中的一个元素并返回True或False。
执行后,filter() 函数返回一个filter 对象。一个filter 对象是一个可迭代的对象,它包含了iterable_object 的所有元素,对于这些元素,input_function 返回True 。
join() 方法被用来从一个给定的可迭代对象中创建一个字符串。当对一个分离器字符串调用时, join() 方法将一个可迭代对象作为其输入参数。
执行后,它返回一个字符串,其中可迭代对象的所有元素都被分隔符分开。
要使用 join() 方法和filter() 函数从 Python 的字符串中去除引号,我们将使用以下步骤。
- 首先,我们将创建一个函数
isNotQuotes(),该函数将一个字符作为其输入参数。如果该字符是一个单引号或双引号字符,它返回False。否则,它将返回True。 - 在这之后,我们将使用
filter()函数来排除字符串中的引号。为此,我们将把isNotQuotes函数作为第一个输入参数,把输入字符串作为第二个参数传给过滤器函数。在执行filter()函数后,我们将得到一个filter对象,其中包含输入字符串中除引号外的所有字符。 - 现在,我们将使用
join()方法来获得输出字符串。为此,我们将使用一个空字符串作为分隔符。我们将通过传递过滤器对象作为其输入参数,对分隔符调用join()方法。
在执行join() 方法后,我们将得到没有任何引号的输出字符串。你可以在下面的例子中观察到这一点。
def isNotQuotes(character):
if character == '"':
return False
if character == "'":
return False
return True
input_string = "Pythonf'orb''eginn'er's"
print("The input string is:", input_string)
filter_object=filter(isNotQuotes,input_string)
newStr = "".join(filter_object)
print("The output string is:", newStr)
输出。
The input string is: Pythonf'orb''eginn'er's
The output string is: Pythonforbeginners
在Python中使用List Comprehension从一个字符串中移除引号
列表理解被用来从现有的可迭代对象中创建一个新的列表。我们可以使用列表理解和 join() 方法来从 Python 中的字符串中移除引号。为此,我们将使用以下步骤。
- 首先,我们将创建一个名为
quotes的列表来存储单引号和双引号字符。 - 然后,我们将使用列表理解法从输入的字符串中获得一个不包括引号的字符列表。
- 一旦我们获得了字符列表,我们将在一个空字符串上调用
join()方法,并将字符列表作为输入参数传递给它。 - 在执行
join()方法后,我们将得到想要的字符串。你可以在下面的例子中观察到这一点。
input_string = "Pythonf'orb''eginn'er's"
print("The input string is:", input_string)
quotes = ["'", '"']
myList = [character for character in input_string if character not in quotes]
newStr = "".join(myList)
print("The output string is:", newStr)
输出。
The input string is: Pythonf'orb''eginn'er's
The output string is: Pythonforbeginners
在Python中使用replace()方法去除字符串中的引号
replace() 方法是用来在一个字符串中用另一个字符替换一个字符。当对一个字符串调用时,replace() 方法把需要替换的元素作为第一个输入参数,把新的字符作为第二个参数。执行后,它返回修改后的字符串。
要使用 replace() 方法从 Python 的字符串中去除引号,我们将使用以下步骤。
- 首先,我们将在输入字符串上调用
replace()方法。在这里,我们将把单引号字符作为第一个输入参数,把一个空字符串作为第二个输入参数传给replace()方法。replace()方法将返回一个字符串,即tempStr作为其输出。 tempStr再次,我们将对replace()方法进行调用。这一次,我们将把双引号字符作为第一个输入参数,把一个空字符串作为第二个输入参数传递给replace()方法。
在第二次执行替换方法后,我们将得到所需的输出字符串,其中没有引号字符。你可以在下面的例子中观察到这一点。
input_string = "Pythonf'orb''eginn'er's"
print("The input string is:", input_string)
tempStr = input_string.replace("'", "")
newStr = tempStr.replace('"', "")
print("The output string is:", newStr)
输出。
The input string is: Pythonf'orb''eginn'er's
The output string is: Pythonforbeginners
在Python中使用re.sub()函数从一个字符串中去除引号
正则表达式 为我们提供了处理字符串的各种函数。我们可以使用re.sub() 函数从Python中的一个字符串中去除引号。
re.sub() 函数的语法如下。
re.sub(old_character, new_character, input_string)
这里。
input_string是我们要替换或删除的字符的字符串。old_character是需要从input_string中删除的字符。new_character是将插入到input_string中的字符,以取代old_character。
在python中使用re.sub() 函数从一个给定的字符串中移除引号,我们将使用单引号和双引号字符作为old_character ,使用一个空字符串作为new_character 。
- 首先,我们将把单引号作为第一个输入参数,把空字符串作为第二个输入参数,把给定的字符串作为第三个输入参数传递给
re.sub()函数。执行后,sub()函数将返回一个字符串。我们将把它命名为tempStr。 - 现在,我们将把双引号作为第一个输入参数,把空字符串作为第二个输入参数,把
tempStr作为第三个输入参数传递给函数re.sub()。
执行后,re.sub() 函数将返回没有引号的所需字符串。你可以在下面的代码中观察到这一点。
import re
input_string = "Pythonf'orb''eginn'er's"
print("The input string is:", input_string)
tempStr = re.sub("'", "", input_string)
newStr = re.sub('"', "", tempStr)
print("The output string is:", newStr)
输出。
The input string is: Pythonf'orb''eginn'er's
The output string is: Pythonforbeginners
从Python字符串中删除第一个和最后一个引号字符
如果我们有一个只在开头和结尾有引号的字符串,如"'Aditya'" 或'"Aditya"' ,我们可以使用以下方法从字符串中去除引号。
使用 ast 模块从一个字符串中去除首尾两个引号字符
ast 模块为我们提供了 literal_eval() 函数,用于评估以字符串形式书写的表达式。literal_eval() 函数将一个字符串作为其输入参数,对其进行评估,并返回输出。
当我们把字符串'"Aditya"' 或"'Aditya'" 传递给literal_eval() 函数时,它认为输入的字符串是表达式,"Aditya" 或 'Aditya' 是相应的值。你可以在下面的例子中观察到这一点。
import ast
input_string = "'Aditya'"
newStr=ast.literal_eval(input_string)
print("The input string is:", input_string)
print("The output string is:", newStr)
输出。
The input string is: 'Aditya'
The output string is: Aditya
如果输入的字符串在与第一个和最后一个位置不同的位置上含有额外的引号,这种方法就不会起作用。如果你试图用literal_eval() 函数从这样的输入字符串中去除引号,程序会遇到SyntaxError ,如下例所示。
import ast
input_string = "'Adity'a'"
print("The input string is:", input_string)
newStr=ast.literal_eval(input_string)
print("The output string is:", newStr)
输出。
The input string is: 'Adity'a'
Traceback (most recent call last):
File "/home/aditya1117/PycharmProjects/pythonProject/string12.py", line 5, in <module>
newStr=ast.literal_eval(input_string)
File "/usr/lib/python3.8/ast.py", line 59, in literal_eval
node_or_string = parse(node_or_string, mode='eval')
File "/usr/lib/python3.8/ast.py", line 47, in parse
return compile(source, filename, mode, flags,
File "<unknown>", line 1
'Adity'a'
^
SyntaxError: invalid syntax
在这种方法中,输入字符串必须在第一个和最后一个位置都包含引号字符。
如果我们在第一个位置有一个引号字符,而在最后一个位置没有,程序将运行到SyntaxError 。同样,如果我们在最后一个位置有一个引号字符,而在第一个位置没有,程序将再次运行到SyntaxError 。
你可以在下面的例子中观察到这一点。
import ast
input_string = "'Aditya"
print("The input string is:", input_string)
newStr=ast.literal_eval(input_string)
print("The output string is:", newStr)
输出。
The input string is: 'Aditya
Traceback (most recent call last):
File "/home/aditya1117/PycharmProjects/pythonProject/string12.py", line 5, in <module>
newStr=ast.literal_eval(input_string)
File "/usr/lib/python3.8/ast.py", line 59, in literal_eval
node_or_string = parse(node_or_string, mode='eval')
File "/usr/lib/python3.8/ast.py", line 47, in parse
return compile(source, filename, mode, flags,
File "<unknown>", line 1
'Aditya
^
SyntaxError: EOL while scanning string literal
另一个需要注意的条件是,字符串开头和结尾的引号字符都应该是一样的。如果字符串的开头有单引号,结尾有双引号,或者相反,程序将再次运行到SyntaxError ,如下图所示。
import ast
input_string = "'Aditya\""
print("The input string is:", input_string)
newStr=ast.literal_eval(input_string)
print("The output string is:", newStr)
输出。
The input string is: 'Aditya"
Traceback (most recent call last):
File "/home/aditya1117/PycharmProjects/pythonProject/string12.py", line 5, in <module>
newStr=ast.literal_eval(input_string)
File "/usr/lib/python3.8/ast.py", line 59, in literal_eval
node_or_string = parse(node_or_string, mode='eval')
File "/usr/lib/python3.8/ast.py", line 47, in parse
return compile(source, filename, mode, flags,
File "<unknown>", line 1
'Aditya"
^
SyntaxError: EOL while scanning string literal
如果输入的字符串在开始和结束时不包含引号字符,程序将遇到ValueError 异常。你可以在下面的例子中观察到这一点。
import ast
input_string = "Aditya"
print("The input string is:", input_string)
newStr = ast.literal_eval(input_string)
print("The output string is:", newStr)
输出。
The input string is: Aditya
Traceback (most recent call last):
File "/home/aditya1117/PycharmProjects/pythonProject/string12.py", line 5, in <module>
newStr = ast.literal_eval(input_string)
File "/usr/lib/python3.8/ast.py", line 99, in literal_eval
return _convert(node_or_string)
File "/usr/lib/python3.8/ast.py", line 98, in _convert
return _convert_signed_num(node)
File "/usr/lib/python3.8/ast.py", line 75, in _convert_signed_num
return _convert_num(node)
File "/usr/lib/python3.8/ast.py", line 66, in _convert_num
_raise_malformed_node(node)
File "/usr/lib/python3.8/ast.py", line 63, in _raise_malformed_node
raise ValueError(f'malformed node or string: {node!r}')
ValueError: malformed node or string: <_ast.Name object at 0x7ffbe7ec60d0>
因此,你应该记住,只有当字符串的开头和结尾都包含引号字符时,你才能使用literal_eval() 函数。
使用eval()函数删除字符串中的第一个和最后一个引号字符
eval() 函数的工作方式与 literal_eval() 函数类似。它也接受一个字符串表达式作为输入参数,对表达式进行评估,并返回结果值。
你可以使用eval() 函数删除字符串中的第一个和最后一个引号,如下所示。
input_string = "'Aditya'"
print("The input string is:", input_string)
newStr = eval(input_string)
print("The output string is:", newStr)
输出。
The input string is: 'Aditya'
The output string is: Aditya
string_eval() 函数中提到的所有条件在eval() 函数中都是真的。因此,你应该记住,你不能对每个字符串都使用eval() 函数。
使用 json 模块删除字符串中的首尾两个引号字符
一个用双引号括起来的python字符串是一个有效的json对象。因此,我们可以使用json 模块从输入字符串的第一个和最后一个位置移除引号。
json模块中的 loads() 函数将一个json对象作为其输入参数,并返回一个与json对象对应的python字符串。
由于我们的字符串在第一个和最后一个位置含有额外的引号。它将被认为是一个有效的json对象。因此,我们可以把它传递给loads() 函数来获得输出字符串,如下所示。
import json
input_string = '"Aditya"'
print("The input string is:", input_string)
newStr = json.loads(input_string)
print("The output string is:", newStr)
输出。
The input string is: "Aditya"
The output string is: Aditya
在这里,你应该记住,带有单引号的字符串不是一个有效的json字符串。因此,如果你试图用json模块从给定的字符串中去除单引号,程序会出现错误,如下例所示。
import json
input_string = "'Aditya'"
print("The input string is:", input_string)
newStr = json.loads(input_string)
print("The output string is:", newStr)
输出。
The input string is: 'Aditya'
Traceback (most recent call last):
File "/home/aditya1117/PycharmProjects/pythonProject/string12.py", line 4, in <module>
newStr = json.loads(input_string)
File "/usr/lib/python3.8/json/__init__.py", line 357, in loads
return _default_decoder.decode(s)
File "/usr/lib/python3.8/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib/python3.8/json/decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
在所有其他情况下,除了额外的双引号,如果你试图从字符串中删除引号,使用json模块的方法将遇到错误。因此,你应该记住,你只能在一种情况下使用这种方法。
使用 strip() 函数从字符串中去除首尾引号字符
使用 ast 模块、json 模块或eval() 函数从字符串的开头和结尾去除引号有很多限制。在使用这些方法时,你的程序极有可能会遇到异常。我们可以使用strip() 方法来删除字符串开头和结尾的引号,而不是上述方法。
strip() 方法,当对一个字符串调用时,需要一个字符作为其输入参数。执行后,它从字符串的开头和结尾删除所有出现的字符,并返回一个新的字符串。
为了从字符串的开头和结尾去除引号,我们将使用以下方法。
- 首先,我们将声明一个字符串
temp1,并将其初始化为输入字符串。 - 现在,我们将使用一个while循环来删除引号字符。在while循环内,我们将使用以下步骤。
- 首先,我们将声明一个名为
temp2的临时字符串,并将其初始化为temp1。 - 现在,我们将在
temp1上调用strip()方法。在这里,我们将传递一个单引号字符作为输入参数给strip()方法。我们将把strip()方法的返回值存储在temp3。 - 再次,我们将在
temp3上调用strip()方法。这一次,我们将把双引号作为输入参数传给strip()方法。我们将把输出存储在temp4。 - 现在,我们将检查
temp4是否等于temp2。如果是,所有的引号已经从字符串中删除,因为在当前的迭代中字符串没有发生变化。因此,我们将使用break语句退出while循环。 - 如果
temp2不等于temp4,那么字符串的开头和结尾仍然包含引号。因此,我们需要再进行一次迭代。为此,我们将把temp4赋给temp1。
在执行while循环后,我们将得到所需的字符串,其开头和结尾的引号已被删除。你可以在下面的代码中看到这一点。
input_string = "'Pythonforbeginners'"
print("The input string is:", input_string)
temp1 = input_string
while True:
temp2 = temp1
tem3 = temp2.strip("'")
temp4 = tem3.strip('"')
if temp4 == temp2:
newStr = temp2
print("The output string is:", newStr)
break
else:
temp1 = temp4
输出。
The input string is: 'Pythonforbeginners'
The output string is: Pythonforbeginners
在literal_eval() 方法和 eval() 函数失败的情况下,这种方法成功地去除了引号。因此,你可以自由地使用这种方法。例如,请看下面的例子。
input_string = "'''''''Pythonforbeginners'\""
print("The input string is:", input_string)
temp1 = input_string
while True:
temp2 = temp1
tem3 = temp2.strip("'")
temp4 = tem3.strip('"')
if temp4 == temp2:
newStr = temp2
print("The output string is:", newStr)
break
else:
temp1 = temp4
输出。
The input string is: '''''''Pythonforbeginners'"
The output string is: Pythonforbeginners
在上面的例子中,你可以观察到我们使用了一个输入字符串,它的左边包含七个单引号,右边是一个带双引号的单引号。即使在这种不对称的情况下,该程序也能正常工作,没有遇到任何错误。
总结
在这篇文章中,我们已经讨论了在Python中从字符串中去除引号的各种方法。在所有这些方法中,我将建议你使用replace() 方法和 re.sub() 函数。使用这些函数的方法是最有效的。