LoginSignup
2
5

More than 3 years have passed since last update.

【Python 初心者メモ】python の文字列、パス操作

Last updated at Posted at 2020-02-03

python を勉強していて、色々と調べますが、いつも同じことを調べるので、自分用メモ的にまとめようと思います。

初投稿です。何かおかしなことがあれば、ご指摘いただけると嬉しいです。

ここでは、python の文字列、パス関連の関数についてまとめます。

os.path.join

join() は、配列などを結合してくれる関数として一般的だと思いますが、
os.path.join() は パスをつなげてくれる関数と理解しています。

たとえば、

osp.join("dir1/", "dir2")
osp.join("dir1",  "dir2")

ともに、

dir1/dir2

を返します。

主な使い方として、以下の2通りがあるようです。

osp.join(path1,  path2)
osp.join(path1 + path2)

引数の先頭に「/」が来ると動作が変わるようです。

path1 = "path1"
path2 = "/path2"
osp.join(path1,  path2) # /path2 を返す
osp.join(path1 + path2) # path1/path2

ちなみに、ある本ではこれを使い分けていましたが、その恩恵はまだわかっていません。。。

リストを使いたい場合は、アスタリスクをつけるとよいそうです。
参照:https://www.sejuku.net/blog/64408

python のアスタリスクについては、以下を参照しました。
https://qiita.com/LouiS0616/items/1bbe0a9bb93054f6c380

format

{} で定義した場所に、format()の引数を置換します。

print("{} は {} 円です".format("ビール", 1000))
# > ビール は 1000 円です

キーワードを指定することもできます。

print("{item} は {price} 円です".format(price=2000, item="刺身"))
# > 刺身 は 2000 円です

dict 型も使えます。

price_list = {"item":"水", "price":500}
print("{item} は {price} 円です".format(**price_list))
# > 水 は 500 円です

% 演算子

あまり推奨されていないという記述もみられますが、本などの記述であったので、残しておこうと思います。

%s、%i などで定義されたものを、% の後の変数で置換します。
sprintf みたいなものだと理解しています。

test_template = "%s は %i 円です"
print((test_template % ("ラーメン",1050)))
# > ラーメン は 1050 円です

おわりに

また調べたことを更新していこうと思います。

2
5
1

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