LoginSignup
1
0

More than 3 years have passed since last update.

[Python]値段・サイズなどの文字列を綺麗なint型に変換する

Last updated at Posted at 2019-12-21

いろんなECサイトをスクレイピングしていると、値段や長さ、重さといった「比較可能な数字なんだけど、表現が多様な文字列」に出くわす。

そんな文字列を一律にきれいなint型に変換する方法のメモ。
(今回は小数点以下は無視して整数型として取り出す)

変換コード

convert.py
# ライブラリのインポート
import re

# 全角半角が混じった小数点つき表現
price = '値段1,800.000円'

def convert(price):
  splitted = price.split('.')
  nums = [re.sub("\\D", "", s) for s in splitted]
  return int([n for n in nums if n != ''][0])

int_price = convert(price)
print(int_price)   # => "1800"

小数点であるコンマと数字表現以外の文字列は無視し、全角半角は全て半角に直した上でint型に変換できた。

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