在 Python 中从字符串中删除引号
用单引号或双引号括起来的字符组合称为一个字符串。本文将介绍在 Python 中从字符串中删除引号的不同方法。
在 Python 中使用 replace()
方法从字符串中删除引号
这个方法需要 2 个参数,可以命名为 old 和 new。我们可以调用 replace()
,用'""'
作为旧字符串,用""
(空字符串)作为新字符串,来删除所有的引号。
完整的示例代码如下。
old_string = '"python"'
new_string = old_string.replace('"', "")
print("The original string is - {}".format(old_string))
print("The converted string is - {}".format(new_string))
输出:
The original string is - "python"
The converted string is - python
在 Python 中使用 strip()
方法从字符串中删除引号
在这个方法中,字符串两端的引号会被删除。在这个函数中传递引号 '""'
作为参数,它将把旧字符串两端的引号去掉,生成不带引号的 new_string
。
完整的示例代码如下。
old_string = '"python"'
new_string = old_string.strip('"')
print("The original string is - {}".format(old_string))
print("The converted string is - {}".format(new_string))
输出:
The original string is - "python"
The converted string is - python
在 Python 中使用 lstrip()
方法从字符串中删除引号
如果引号出现在字符串的开头,本方法将删除它们。它适用于需要删除字符串开头的引号的情况。
完整的示例代码如下。
old_string = '"python'
new_string = old_string.lstrip('"')
print("The original string is - {}".format(old_string))
print("The converted string is - {}".format(new_string))
输出:
The original string is - "python
The converted string is - python
在 Python 中使用 rstrip()
方法从字符串中删除引号
如果引号出现在字符串的末尾,本方法将删除引号。当没有参数传入时,默认要删除的尾部字符是白色空格。
完整的示例代码如下。
old_string = 'python"'
new_string = old_string.rstrip('"')
print("The original string is - {}".format(old_string))
print("The converted string is - {}".format(new_string))
输出:
The original string is - python"
The converted string is - python
在 Python 中使用 literal_eval()
方法从字符串中删除引号
此方法将测试一个 Python 字符或容器视图表达式节点、Unicode 或 Latin-1 编码的字符串。提供的字符串或节点只能由以下 Python 结构组成:字符串、数字、元组、列表、字典、布尔值等。它可以安全地测试包含不受信任的 Python 值的字符串,而不需要检查值本身。
完整的示例代码如下。
string = "'Python Programming'"
output = eval(string)
print(output)
输出:
Python Programming
相关文章
Pandas DataFrame DataFrame.shift() 函数
发布时间:2024/04/24 浏览次数:133 分类:Python
-
DataFrame.shift() 函数是将 DataFrame 的索引按指定的周期数进行移位。
Python pandas.pivot_table() 函数
发布时间:2024/04/24 浏览次数:82 分类:Python
-
Python Pandas pivot_table()函数通过对数据进行汇总,避免了数据的重复。
Pandas read_csv()函数
发布时间:2024/04/24 浏览次数:254 分类:Python
-
Pandas read_csv()函数将指定的逗号分隔值(csv)文件读取到 DataFrame 中。
Pandas 多列合并
发布时间:2024/04/24 浏览次数:628 分类:Python
-
本教程介绍了如何在 Pandas 中使用 DataFrame.merge()方法合并两个 DataFrames。
Pandas loc vs iloc
发布时间:2024/04/24 浏览次数:837 分类:Python
-
本教程介绍了如何使用 Python 中的 loc 和 iloc 从 Pandas DataFrame 中过滤数据。
在 Python 中将 Pandas 系列的日期时间转换为字符串
发布时间:2024/04/24 浏览次数:894 分类:Python
-
了解如何在 Python 中将 Pandas 系列日期时间转换为字符串