拼接字符串,用于从第一个空格的左侧和右侧空格的右侧获取所有内容



我有这个字符串,我想拼接"$14.79 到 $39.79"。我想要的是将 $14.79 分配给它自己的字符串变量(已经有逻辑去掉 $ 并转换为浮点数(,将 $39.79 分配给它自己的字符串变量。我该怎么做?美元金额可能会发生变化(即 560.95 美元、4.55 美元等(,但无论如何,"空间到空间"将始终存在。

你可以用空格分割你的字符串,然后删除to字符串 像下面的代码

currency = "$300 to $50000"
# split by space
splitted = currency.split(" ")
# remove to keyword
del splitted[1]
print(splitted)
# it will print a list ['$300', '$50000']
# you can join it or anything you want to do

或者你可以喜欢这个

currency = "$300 to $50000"
# split by space
splitted = currency.split(" ")
# remove to keyword
splitted.remove('to')
print(splitted)
# it will print a list again ['$300', '$50000']
s = '$14.79 to $39.79'
v1, *_, v2 = s.split()
print(v1, v2)

指纹:

$14.79 $39.79

或者使用re(这也将删除$(:

import re
v1, v2 = re.findall('[d.]+', s)
print(v1, v2)

指纹:

14.79 39.79

最新更新