0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

[python]raw文字列について

0
Posted at

raw文字列とは?

文字列の前に r または R をつけることで、バックスラッシュ(\)をエスケープ処理せず、そのまま文字として扱う文字列です。

# 通常の文字列
print("C:\new\folder")   # C:
                          #  ew\folder  (\nが改行として解釈される)

# raw文字列
print(r"C:\new\folder")  # C:\new\folder  (そのまま表示)

よく使う場面

1. ファイルパス(Windowsパス)

# 通常(バックスラッシュをエスケープする必要がある)
path = "C:\\Users\\username\\Desktop\\file.txt"

# rawを使うとスッキリ
path = r"C:\Users\username\Desktop\file.txt"

2. 正規表現

import re

# 通常(ダブルバックスラッシュが必要で読みにくい)
pattern = "\\d+\\.\\d+"

# rawを使うとスッキリ
pattern = r"\d+\.\d+"

result = re.findall(r"\d+", "abc123def456")
print(result)  # ['123', '456']

3. エスケープシーケンスを無効化したい時

print("\t")    # タブ文字
print(r"\t")   # \t という文字そのまま

print("\n")    # 改行
print(r"\n")   # \n という文字そのまま

注意点

バックスラッシュで終わることはできない

# エラーになる
path = r"C:\Users\"   # SyntaxError

# 回避方法
path = r"C:\Users" + "\\"
# または
path = "C:\\Users\\"

raw文字列の中身はあくまで文字列

type(r"hello")  # <class 'str'>  普通のstrと同じ型

エスケープシーケンス一覧(rawで無効化できるもの)

シーケンス 意味
\n 改行
\t タブ
\r キャリッジリターン
\\ バックスラッシュ
\' シングルクォート
\" ダブルクォート

まとめ

  • r"..." でバックスラッシュをそのまま扱える
  • 正規表現Windowsパスで特に便利
  • 末尾をバックスラッシュで終わらせることはできない

何か具体的な使いたい場面があればお気軽にどうぞ!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?