LoginSignup
2
10

More than 3 years have passed since last update.

Pythonで数字や文字列を判定しよう!

Last updated at Posted at 2019-06-19

こんにちは!
今回は僕が「こんなことできるのか!」と思ったことを紹介します。
ぜひ、最後まで読んでください。

数字か文字列か判定できる!

僕がHakcerRankを解いている中で出会ったのが数字かどうか判定できる機能です。
今回はGoogleを検索しているうちに見つけたものをご紹介します。

str.isdecimal()

str.isdecimal()を使用すると、半角・全角のアラビア数字が真、それ以外は偽で返してくれます

a="10"
if a.isdecimal():
    print(True)
else:
    print(False)
#True

a="10"
if a.isdecimal():
    print(True)
else:
    print(False)
#True

a="ten"
if a.isdecimal():
    print(True)
else:
    print(False)
#False

str.isdigit()

str.isdigit()は半角・全角のアラビア数字と特殊数字を真、それ以外を偽で返してくれます
str.digit()はstr.isdecimal()が特殊数字も真で返してくれるバージョンになったと考えるといいかもしれません。

a='①'
if a.isdigit():
    print(True)
else:
    print(False)
#True

str.isnumeric()

str.isnumeric()では半角・全角のアラビア数字、特殊数字、漢数字を真、それ以外を偽で返してくれます
こちらも上記で紹介したものに漢数字が含まれたと考えればいいでしょう。

a="十"
if a.isnumeric:
    print(True)
else:
    print(False)
#False

大文字か小文字かの判定

そしてPythonでは大文字か小文字か判定するための機能があるそうです!
そちらについてもちらっと紹介します。

str.isupper()

str.isupper()では大文字の場合は真、それ以外の場合は偽で返します。

a='ABC'
if a.isupper():
    print(True)
else:
    print(False)
#True

a='abc'
if a.isupper():
    print(True)
else:
    print(False)
#False

str.islower()

str.islowerでは小文字の場合は真、それ以外の場合は偽で返してくれます。

a='abc'
if a.islower():
    print(True)
else:
    print(False)
#True

a='ABC'
if a.islower():
    print(True)
else:
    print(False)
#False

まとめ

今回は文字列の判定について紹介させていただきました。
こんな便利な機能があると知らなかったので、色々勉強になりました。
これらの機能はバリデーションなどに使えそうですね。
まだまだ、勉強不足なのでこれからも勉強していきます。
最後まで読んでいただきありがとうございます。

参考文献

Pythonの文字列判定に関する記事
数字の判定の記事

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