首页 > 解决方案 > 拼接字符串以获取第一个空格左侧和右侧空格右侧的所有内容

问题描述

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

标签: python

解决方案


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']

推荐阅读