1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Udemy】Python動画講義学習 記録#3

1
Posted at

はじめに

こんにちは!Python学習に励む皆さんの並走者として、今日も学習記録をお届けします。

現在、私はUdemyの人気講座「現役シリコンバレーエンジニアが教えるPython 3 入門 + 応用 +アメリカのシリコンバレー流コードスタイル」で、酒井潤先生からプロフェッショナルなコードの書き方を学んでいます。

3日目の今日は、プログラミングで欠かせない「文字列の操作」について深掘りしました。

今日学んだこと

  • 文字列メソッドの活用(検索、置換、大文字化など)
  • 文字列への代入(.formatメソッド)
  • データ型の変換(str関数)
  • 最新の書き方「f-strings」

1. 知っていると便利な「文字列メソッド」

Pythonには、文字列を便利に加工するための「メソッド」がたくさん用意されています。今回は特によく使うものをピックアップしました。

  • startswith: 特定の文字で始まっているか判定します。
  • find: 指定した文字がどこにあるか数字(インデックス)で返します。
  • upper / replace: 文字を大文字にしたり、特定の単語を別の単語に置き換えたりします。
s = "My name is Mike. Hi Mike."

print(s.startswith("My"))         # 結果: True
print(s.find("Mike"))            # 結果: 11 (11番目にある)
print(s.upper())                 # 結果: MY NAME IS MIKE. HI MIKE.
print(s.replace("Mike", "Nancy")) # 結果: My name is Nancy. Hi Nancy.

2. 文字列の代入:.format() の使い方

文字列の中に変数の値を埋め込みたいとき、.format()を使うとスマートに書けます。

インデックス番号やキーワードで指定

引数の順番(0, 1...)で指定する方法や、変数名(キーワード)を割り当てる方法があります。後者の方が、どの場所に何を入れようとしているのか一目でわかるのでオススメです。

# インデックス指定
print("My name is {0} {1}".format("taro", "nihon"))

# キーワード指定
print("My name is {name} {family}".format(name="taro", family="nihon"))

3. 型変換(str)の重要性

Pythonでは、数字(intやfloat)と文字列(str)をそのまま足し算することはできません。数字を文字列として扱いたいときは、str()を使って型を変換してあげる必要があります。

x = str(3.14) # float型の3.14を、文字列の"3.14"に変換

4. f-strings

最後に学んだのが、Python 3.6から登場したf-stringsです。これが驚くほどシンプルで書きやすいんです!

文字列の先頭にfをつけるだけで、{}の中に直接変数名を書くことができます。

name = "taro"
family = "nihon"

# f-stringsならこれだけでOK!
print(f"My name is {name} {family}")

感想:

今日の学習で一番印象に残ったのは、.format()からf-stringsへの進化です。

教材が作成された当初は.format()だったそうですが、後から登場したf-stringsの方が圧倒的に直感的で、タイピング量も少なくて済みます。プログラミング言語も日々使いやすく進化しているんだな、と実感した1日でした。

初心者のうちは最新の書き方を積極的に取り入れて、読みやすいコードを目指していきたいですね!


1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?