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?

More than 3 years have passed since last update.

Pythonの文字列操作 覚え書き

0
Last updated at Posted at 2023-06-04

文字列操作の基本

「退屈なことはPythonにやらせよう 第2版 ―ノンプログラマーにもできる自動化処理プログラミング」 https://amzn.asia/d/gMU3h2f
より抜粋してメモ化。例の関数など、適宜改変を加えてある。節番号が表記してあるので、原典を参照されたし。

escape文字 (6.1.1.2)

  • 表6-1
escape文字 意味
\' シングルquote
\" ダブルquote
\t tab
\n 改行
\\ バックスラッシュ

raw 文字列 (6.1.1.3)

quote文字列の前にrをつけると、raw文字列を表す。
raw文字列では、文字列中のエスケープ文字が無視される。
正規表現のように、たくさんのバックスラッシュを含むときに便利。

>>> print(r"That is Taro\'s cat.")
That is Taro\'s cat.

三連quoteによる複数行文字列 (6.1.1.4)

エスケープ文字\nでも文字列に改行を入れられるが、複数業の文字列をまとめて扱う場合は、三連quoteが便利。

>>> print("""Hello!
2nd line
    3rd line
    See you!
""")
Hello!
2nd line
    3rd line
    See you!

複数行コメント (6.1.1.5)

#で1行ずつコメントアウトできるが、まとめてコメントアウトしたい時には、三連quoteが使える。

def hogehoge():
    """
    This is the function to do hogehoge.
    You can execute the function by `hogehoge()`
    """
    print("Hello!")

hogehoge()

得られる出力は、

Hello!

文字列のなかに文字列を挿入する (6.2)

%演算子を用いて、文字列中のマーカーを後ろに並べた値に置き換えることができる。
文字列補完の利点はstr()で数字を文字列に変換する必要がない点。

name = "Taro"
age = 20
print("My name is %s. I am %d years old." % (name, age))

得られる出力は、

My name is Taro. I am 20 years old.

さらに、Python3.6以降では、f文字列が使えるようになった。
その場合は、%sではなく、{}をつかってその中に式を直接かく。
raw文字列のように、引用記号の前にfをつける。

name = "Taro"
age = 20
print(f"My name is {name}. Next year, I will be {age+1}.")

得られる出力は、

My name is Taro. Next year, I will be 21.
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?