Pythonでは、文字列から数字を抽出する方法は何ですか?
文字列から数字を抽出するには、正規表現や組み込みの文字列メソッドを使用することができます。
正規表現を使用する。
import re
s = "abc123def456"
numbers = re.findall(r'\d+', s)
print(numbers) # ['123', '456']
文字列のメソッドを使用する。
s = "abc123def456"
numbers = ''.join(filter(str.isdigit, s))
print(numbers) # '123456'
浮動小数点数を取得するには、少し変更することができます。
import re
s = "abc1.23def4.56"
numbers = re.findall(r'\d+\.\d+', s)
print(numbers) # ['1.23', '4.56']
s = "abc1.23def4.56"
numbers = ''.join(filter(lambda x: x.isdigit() or x == '.', s))
print(numbers) # '1.234.56'