LoginSignup
4
3

More than 3 years have passed since last update.

【Python初心者】住所から都道府県と市区町村を抜き出す(3行)。

Posted at

結論

都道府県
import re
#都道府県のみ
address = "東京都新宿区西新宿1-1-1"
matches = re.match('東京都|北海道|(?:京都|大阪)府|.{2,3}県' , address)
print(matches.group()) 
#--->東京都
import re
#区のみ
address = "東京都新宿区西新宿1-1-1"
ku_number = address.find('区')
print(address[:ku_number+1])  #ない場合は空白が返される
#--->東京都新宿区
import re
#市のみ
address = "東京都八王子市横山町1-1"
shi_number = address.find('市')
print(address[:shi_number+1])  #ない場合は空白が返される  #ない場合は空白が返される
#--->東京都八王子市

町村も同じく.find()で得ることができる。

4
3
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
4
3