嘿,我正在尝试解决这个问题,我已经搜索了stackoverflow,但是没有找到正确的答案,所以我有price
并且包含
$ 250.88-$ 650.86
或
$ 650.86
我想查找给定的price
中是否包含-
,然后条件变为真并删除$250.88 -
并仅打印
680.86
这是我写的代码,但是没有用:
price = '$250 - $650.86'
if (price[price.rfind('-'):]):
val = price[price.rfind('-'):]
trim = re.compile(r'[^\d.,]+')
price2 = trim.sub('', val)
else:
price2 = trim.sub('', price)
print(price2)
答案 0 :(得分:2)
testcases = [
'$250.88 - $650.86',
'$650.86',
'$568.6'
]
for case in testcases:
price = case.split('-')[-1].replace('$', '').strip()
print(price)
打印:
650.86
650.86
568.6
要检查-
是否在price
字符串中,可以使用-
运算符:
testcases = [
'$250.88 - $650.86',
'$650.86',
'$568.6'
]
for case in testcases:
price = case.split('-')[-1].replace('$', '').strip()
if '-' in case:
print('Price "{}" contains -'.format(case))
else:
print('Price "{}" doesn\'t contain -'.format(case))
print(price)
打印:
Price "$250.88 - $650.86" contains -
650.86
Price "$650.86" doesn't contain -
650.86
Price "$568.6" doesn't contain -
568.6
答案 1 :(得分:1)
您可以使用var query = from trans in Translation
group trans by trans.key into transGroup
select new
{
transGroup.Key,
Values = from langId in Languages
join trans in transGroup on langId equals trans.cultureId
into joint
from trans in joint.DefaultIfEmpty()
select trans?.value
};
var values = query.ToDictionary(x => x.Key, x => x.Values.ToList());
来简化操作,如下所示:
split
希望有帮助。
答案 2 :(得分:0)
您可以使用split()
函数:
price = '$250 - $650.86'
# The first [1] chooses the part of the string after the '-'
# The second [1] removes the space
if len(price.split('-'))>1:
price = price.split('-')[1][1:]
输出:
'$650.86'
答案 3 :(得分:0)
您的代码过于复杂。 Python具有一项不错的功能,您可以轻松检查一个对象是否属于迭代对象,因此在您的情况下,我们可以检查一个字符串是否在另一个字符串中:
if '-' in price:
...
编辑:问题的第二部分
由于您已经在使用re模块:
if '-' in price:
matches = re.findall(r'\$(\d+(?:\.\d+)?)', price)
print(matches[-1])
else:
print(price.strip('$'))
无论是否存在减号,正则表达式都将起作用,但是RE往往会变慢,所以我会尽量避免使用它们。
答案 4 :(得分:0)
您可以find
索引-
并返回一个子字符串,如果没有-
则返回该字符串
price = '$250 - $650.86'
def get_last_part(p):
i = price.find('-')
if i > 0:
return p[i+1:].strip()
return p
print(get_last_part(price))
print(get_last_part('$250'))
如果您也想删除美元符号,可以将其删除
.strip('- $')
答案 5 :(得分:0)
您可以简单地执行以下操作:
price = '$250 - $650.86'
if '-' in price:
print(price.split()[-1])
else:
print(price.split()[0])
答案 6 :(得分:0)
if '-' in price:
price.strip()
c = price.rfind('-')
c = c+1
price2 = price[c:]
else:
price 2 = trim.sub('',price)
print(price2)
我认为这是一个简短的解决方案。
答案 7 :(得分:0)
一个班轮
testcases = [
'$250.88 - $650.86',
'$650.86',
'$568.6'
]
[ i.split('-')[-1] for i in testcases ]