Pythonで文字列の引用符を削除する方法

Python では次の方法で文字列のクォートを取り除くことができます。

  1. strip()
string = '"Hello, World!"'
new_string = string.strip('"')
print(new_string)  # Output: Hello, World!
  1. シングルクォートを削除したい文字列をスライスします。
string = '"Hello, World!"'
new_string = string[1:-1]
print(new_string)  # Output: Hello, World!
  1. 代わりに置き換える
string = '"Hello, World!"'
new_string = string.replace('"', '')
print(new_string)  # Output: Hello, World!

但し、このやり方では文字列の両側の引用符しか消さないので、文字列中に引用符が含まれている場合には適宜対処する必要があります。

bannerAds