我有几个字符串,如下所示。如何获得除小数点之外的点?
请注意:我需要小数点后的数字。我不想在那之后丢失小数点和数字。
例如:
"8.2"
"88.2"
"888.2"
"8.888.2"
"8.888.888.2"
输出将如下所示:
"8.2"
"88.2"
"888.2"
"8888.2"
"8888888.2"
使用str.rpartition
.即使输入中没有.
,它也会正常工作,如下所示。
def fix_number(n):
a, sep, b = n.rpartition(".")
return a.replace(".", "") + sep + b
for case in ["8.2", "88.2", "888.2", "8.888.2", "8.888.888.2", "8"]:
print(case, fix_number(case))
8.2 8.2
88.2 88.2
888.2 888.2
8.888.2 8888.2
8.888.888.2 8888888.2
8 8
一种方法是在点上拆分,然后连接在一起,特别处理最后一个:
s = '8.888.888.2'
*whole, decimal = s.split('.')
res = ''.join(whole) + '.' + decimal # gives: 8888888.2
如果要将千位和/或小数分隔符替换为其他字符,可以使用类似的方法:
s = '8.888.888.2'
*whole, decimal = s.split('.')
res = "'".join(whole) + ',' + decimal # gives: 8'888'888,2
另一个想法是用可选的第三个参数count
调用str.replace()
,这将仅替换字符的前count
次出现。
如果我们将count
设置为等于the number of "." minus one
则得到所需的结果:
words = ["8.2", "88.2", "888.2", "8.888.2", "8.888.888.2"]
new_words = []
for word in words:
new_word = word.replace('.', '', word.count('.')-1)
new_words.append(new_word)
print(new_words)
输出
['8.2', '88.2', '888.2', '8888.2', '8888888.2']
我将代码分解为更简单的行,以便更好地理解和可读。
试试这个:
words = ["8", "8.2", "88.2", "888.2", "8.888.2", "8.888.888.2"]
changed_word = []
for word in words:
split_word = word.split(".")
if len(split_word) > 2:
before_decimal = "".join(split_word[0:len(split_word)-1])
after_decimal = split_word[-1]
final_word = before_decimal + "." + after_decimal
else:
final_word = word
changed_word.append(final_word)
print(changed_word)
输出为:
['8', '8.2', '88.2', '888.2', '8888.2', '8888888.2']
下一步:尝试在更少的行数中优化此代码。
你可以在这里使用 re。
.(?=.*.)
只需替换为empty string
.
请参阅演示。
https://regex101.com/r/T9iX3B/1
import re
regex = r".(?=.*.)"
test_str = (""8.2"nn"
""88.2"nn"
""888.2"nn"
""8.888.2"nn"
""8.888.888.2" n"
"8nn"
"the out put will be like this:nn"
" ")
subst = ""
# You can manually specify the number of replacements by changing the 4th argument
result = re.sub(regex, subst, test_str, 0, re.MULTILINE)
if result:
print (result)
x = "8.888.888.22"
y = x.split(".")
z = "".join(y[:-1]) + "." + y[-1]
print(z)
# '8888888.22'
a = ["8", "8.2", "88.2", "888.2", "8.888.2", "8.888.888.2"]
for x in a:
if '.' not in x:
print(x)
continue
ridx = x.rindex('.')
print(x[:ridx].replace('.', '') + x[ridx:])
你需要找到点(.)的最后一个出现位置。然后在该索引之前,将所有点替换为空字符,并添加字符串的剩余部分:
s = "8.888.888.2"
last = -1
for index, item in enumerate(s):
if item == ".":
last = max(index, last)
if last != -1:
s = s[:last].replace(".", "") + s[last:]
print(s)
我可以想象有两种方法来解决您的问题。
第一个是通过将字符串解析为另一个变量
example = 8888888.2
example = str(example) # In case that your input was in another type format
example_1 = example[-1:]
在这种情况下,输出将为"2"。
对于第二种方式,您可以简单地将字符串拆分为一个列表,然后您只得到您想要的内容:
example = 8888888.2
example = str(example)
example_2 = example.split('.') # Inside the parenthesis you can put the element you want to split the string, like a space, a comma, a dot
example_output = example[1]
在这种情况下,输出仍然是相同的"2",在这两种情况下,您都维护基本变量,以防万一您想要原始输入。
一个更简单的函数:
def remove_dot(word):
dot_cnt = word.count('.')
if dot_cnt <= 1:
return word
else:
word = word.replace(".", "", dot_cnt - 1)
return word
print(remove_dot("8.888.888.2"))
输出 : =8888888.2
另一种解决方案,没有特殊功能 (灵感来自@AKX的答案)。
def fix_number(n):
return int( n.replace(".","") ) / ( 10 ** ('.' in n) )
for case in ["8.2", "88.2", "888.2", "8.888.2", "8.888.888.2", "8", ""8.888.888"]:
print(case, fix_number(case))
这个想法是,如果没有点,'.' in n
返回 0 (False),在这种情况下,我们除以 10^0 = 1。如果有一个或多个点,则返回 1 (True),在这种情况下,我们除以 10。
8.2 8.2
88.2 88.2
888.2 888.2
8.888.2 8888.2
8.888.888.2 8888888.2
8 8.0
8.888.888 888888.8 <- not correct
如您所见,即使没有小数,它也返回浮点数。不是OP问的,但我认为这是一个很好的功能:)。但是,它在最后一个测试用例上失败(不在 OP 的示例之列)。
对于这种情况,我们可以将函数替换为
def fix_number(n):
return int( n.replace(".","") ) / ( 10 ** ('.' == n[-2]) )
但这在8
上失败了.
修复导致我们
def fix_number(n):
return int( n.replace(".","") ) / ( 10 ** (n.rfind('.') == max(0,len(n)-2)) )
哪些输出
8.2 8.2
88.2 88.2
888.2 888.2
8.888.2 8888.2
8.888.888.2 8888888.2
8 8.0
8.888.888 8888888.0
但在这一点上,:)有点荒谬。此外,@AKX的答案大约快 3.5 倍。