迹忆客 专注技术分享

当前位置:主页 > 学无止境 > 编程语言 > Python >

在 Python 中从字符串中删除引号

作者:迹忆客 最近更新:2023/12/17 浏览次数:

用单引号或双引号括起来的字符组合称为一个字符串。本文将介绍在 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

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Pandas read_csv()函数

发布时间:2024/04/24 浏览次数:254 分类:Python

Pandas read_csv()函数将指定的逗号分隔值(csv)文件读取到 DataFrame 中。

Pandas 追加数据到 CSV 中

发布时间:2024/04/24 浏览次数:352 分类:Python

本教程演示了如何在追加模式下使用 to_csv()向现有的 CSV 文件添加数据。

Pandas 多列合并

发布时间:2024/04/24 浏览次数:628 分类:Python

本教程介绍了如何在 Pandas 中使用 DataFrame.merge()方法合并两个 DataFrames。

Pandas loc vs iloc

发布时间:2024/04/24 浏览次数:837 分类:Python

本教程介绍了如何使用 Python 中的 loc 和 iloc 从 Pandas DataFrame 中过滤数据。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便