LoginSignup
6
5

More than 5 years have passed since last update.

raw文字列(r'...')を使うとエスケープが多い文字列が楽に書ける

Last updated at Posted at 2017-12-14

この記事は Pythonのコードを短く簡潔に書くテクニック Advent Calendar 2017 の15日目です。

はじめに

例えばWindowsのファイルパスを文字列リテラルで書こうとすると、パス区切文字\をエスケープしなくてはならないので面倒です。
raw文字列を使うと\を通常の文字として扱うため楽に書けるようになります。

普通の文字列で書いた場合

>>> 'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe'
'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe'

raw文字列で書いた場合

raw文字列はr'...'という書き方をします。

>>> r'C:\Program Files (x86)\Google\Chrome\Application\chrome.exe'
'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe'

参考

6
5
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
6
5