ナンクル力学系

学んだ事を書き連ねていこう。

Pythonで文字列が数字か確認する方法

leave a comment »

Pythonで文字列を数字に変換するのはint(“01”)で出来る。でも、数字以外をint(“hoge”)とかしてしまうとエラーが出るので文字列が数字か確認しなきゃいけない。

正規表現かー。面倒だな、と思ってたら普通に関数があった。str.isdigit()でいける。

In [1]: int("hoge")
---------------------------------------------------------------------------
<type 'exceptions.ValueError'>            Traceback (most recent call last)

/home/takafumi/test/pickle_vs_fromfile/<ipython console> in <module>()

<type 'exceptions.ValueError'>: invalid literal for int() with base 10: 'hoge'

In [2]: "hoge".isdigit()
Out[2]: False

In [3]: "001".isdigit()
Out[3]: True

In [4]: "101".isdigit()
Out[4]: True

In [5]: "hoge".isdigit()
Out[5]: False

In [6]: "0hoge".isdigit()
Out[6]: False

In [7]: "023 ".isdigit()
Out[7]: False

参考:2.3.6.1 文字列メソッド

Advertisements

Written by tkf

September 27, 2008 at 12:49 pm

Posted in programming

Tagged with

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: