python去除字符串中的引号

  • Post category:Python

当字符串中含有引号时,我们有时需要将其去掉,这时可以使用 Python 内置的字符串函数 strip() 或 replace()。

使用 strip() 函数

original_string = '"Hello, World!"'
new_string = original_string.strip('"')
print(new_string)

输出结果为:

Hello, World!

strip() 函数会从字符串两端开始搜索,若遇到引号,则将其去除,最终返回去除引号后的字符串。

使用 replace() 函数

original_string = '"Hello, World!"'
new_string = original_string.replace('"', '')
print(new_string)

输出结果为:

Hello, World!

replace() 函数会遍历整个字符串并将其中的所有指定字符替换为另一个指定字符(或空字符)。

除了 strip() 和 replace() 函数外,Python 中还有很多其他能够处理字符串的函数,具体使用则需要根据需求来选择最合适的函数。