Help us understand the problem. What is going on with this article?

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

いろんな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型に変換できた。

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした