【发布时间】:2021-02-09 21:29:52
【问题描述】:
我希望在 python 中编写一个函数,将小数点放入某个字符串中。
例如,如果我给出的字符串是'12355',然后我把点放在2
输出应该跳过前两个数字并显示'12.355'
请帮忙, 谢谢
【问题讨论】:
-
这能回答你的问题吗? Add string in a certain position in Python
我希望在 python 中编写一个函数,将小数点放入某个字符串中。
例如,如果我给出的字符串是'12355',然后我把点放在2
输出应该跳过前两个数字并显示'12.355'
请帮忙, 谢谢
【问题讨论】:
这里
place = 3
number = "12345"
result = number[:place] + "." + number[place:]
print(result)
结果将从第一个小数点开始 3 个字符。 当我运行它时,输出是
123.45
如果你要做一个函数,那么
def insert_decimal(position,number):
return number[:position] + "." + number[position:]
【讨论】:
您可以使用字符串索引,就好像它是一个列表:
def insert_decimal_point(number, position):
return number[:position] + "." + number[position:]
【讨论】:
def add_decimal_point(s, n):
return f'{s[:n]}.{s[n:]}' if 0 < n < len(s) else s
add_decimal_point("23567", 2)
23.567
如果n大于等于字符串的长度,或者为负数,则返回原字符串:
add_decimal_point("23567", 10)
23567
【讨论】:
或者您可以在数学上将此字符串视为一个数字:
s = "12355"
n = float(s)
length = len(s)
place = 2
power = length - place
print(n / (10 ** power))
让逻辑分离到函数中:
def decimal_point(s, place):
n = float(s)
length = len(s)
power = length - place
return n / (10 ** power)
【讨论】: