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のisdigit()を使ってみた

Posted at

はじめに

今回は LeetCode の Evaluate Reverse Polish Notation という問題を解く際に、Python の isdigit() メソッドを使ってみたので、その記録を残しておこうと思う

isdigit()について

isdigit() メソッドは、Python の文字列型 (str) のメソッドで、文字列がすべて数字 (0-9) で構成されているかどうかを判定する時に使う

使い方 :

  • 文字列がすべて数字の場合→True を返す
  • 数字以外の文字を含む、空文字列の場合など は False を返す

注意点 :

  • isdigit()メソッドは、文字列の各文字が数字であるかをチェックする。
    → そのため、整数や浮動小数点、正負の符号は考慮しない
  • あくまで、文字列が数字かどうかを判定するので、実際に数値として使う時は、int(), float()で変換する必要がある

サンプルコード

print("12345".isdigit())    # True  (すべて数字)
print("123.45".isdigit())   # False (小数点が含まれる)
print("-123".isdigit())     # False (マイナス記号が含まれる)
print("123a".isdigit())    # False (アルファベットが含まれる)
print("".isdigit())        # False (空文字列)

ただし、注意点として、マイナスの数字("-123"など)は isdigit() では False になってしまう。そのため、文字列の先頭がマイナス記号の場合、マイナス記号を除いた部分で isdigit() を使用するなどの工夫が必要になる。

print("-123"[1:].isdigit()) # True (マイナス記号を除いた部分が数字)
0
0
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
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?