仅从 Python 中的字符串获取第一个数字
getting only the first Number from String in Python
我目前面临的问题是我有一个字符串,我只想提取其中的第一个数字。我的第一步是从字符串中提取数字。
Headline = "redirectDetail('27184','2 -New-York-Explorer-Pass')"
print (re.findall('\d+', headline ))
Output is ['27184', '2']
在这种情况下,它返回了两个数字,但我只想得到第一个“27184”。
因此,我尝试使用以下代码:
print (re.findall('/^[^\d]*(\d+)/', headline ))
但它不起作用:
Output:[]
你们能帮帮我吗?感谢任何反馈
只需使用 re.search
,它会在找到匹配项后停止匹配。
re.search(r'\d+', headline).group()
或
您必须删除正则表达式中的正斜杠。
re.findall(r'^\D*(\d+)', headline)
re.search('[0-9]+', headline).group()
没有正则表达式的解决方案(不一定更好):
import string
no_digits = string.printable[10:]
headline = "redirectDetail('27184','2 -New-York-Explorer-Pass')"
trans = str.maketrans(no_digits, " "*len(no_digits))
print(headline.translate(trans).split()[0])
>>> 27184
在我的例子中,我也想获得字符串中的第一个数字和货币,我尝试了所有的解决方案,有些返回了没有点的数字,有些返回了我这样做的数字
priceString = "Rs249.5"
def advancedSplit(unformatedtext):
custom_numbers = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
priceList = []
str_length = len(unformatedtext)
index = 0
for l in range(len(unformatedtext)):
if unformatedtext[l] in custom_numbers:
price = unformatedtext[slice(l, len(unformatedtext))]
currency = unformatedtext[slice(0,l)]
priceList.append(currency)
priceList.append(price)
break
elif index == str_length:
priceList.append("")
priceList.append("unformatedtext")
break
else:
continue
index += 1
return priceList
print(advancedSplit(priceString))
为了确保列表的长度始终为 2,我添加了 elif 以防 priceString 只是“249.5”,因为我在网络抓取中使用它
我目前面临的问题是我有一个字符串,我只想提取其中的第一个数字。我的第一步是从字符串中提取数字。
Headline = "redirectDetail('27184','2 -New-York-Explorer-Pass')"
print (re.findall('\d+', headline ))
Output is ['27184', '2']
在这种情况下,它返回了两个数字,但我只想得到第一个“27184”。
因此,我尝试使用以下代码:
print (re.findall('/^[^\d]*(\d+)/', headline ))
但它不起作用:
Output:[]
你们能帮帮我吗?感谢任何反馈
只需使用 re.search
,它会在找到匹配项后停止匹配。
re.search(r'\d+', headline).group()
或
您必须删除正则表达式中的正斜杠。
re.findall(r'^\D*(\d+)', headline)
re.search('[0-9]+', headline).group()
没有正则表达式的解决方案(不一定更好):
import string
no_digits = string.printable[10:]
headline = "redirectDetail('27184','2 -New-York-Explorer-Pass')"
trans = str.maketrans(no_digits, " "*len(no_digits))
print(headline.translate(trans).split()[0])
>>> 27184
在我的例子中,我也想获得字符串中的第一个数字和货币,我尝试了所有的解决方案,有些返回了没有点的数字,有些返回了我这样做的数字
priceString = "Rs249.5"
def advancedSplit(unformatedtext):
custom_numbers = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
priceList = []
str_length = len(unformatedtext)
index = 0
for l in range(len(unformatedtext)):
if unformatedtext[l] in custom_numbers:
price = unformatedtext[slice(l, len(unformatedtext))]
currency = unformatedtext[slice(0,l)]
priceList.append(currency)
priceList.append(price)
break
elif index == str_length:
priceList.append("")
priceList.append("unformatedtext")
break
else:
continue
index += 1
return priceList
print(advancedSplit(priceString))
为了确保列表的长度始终为 2,我添加了 elif 以防 priceString 只是“249.5”,因为我在网络抓取中使用它