gpt4 book ai didi

python - Python 中从字符串末尾开始按 N 个符号分割字符串

转载 作者:行者123 更新时间:2023-12-02 01:51:39 25 4
gpt4 key购买 nike

我需要从末尾分割字符串。例如我有

word = '3640000'

使用列表生成器和 .join 方法可以轻松地将其从字符串的开头拆分:

word = ' '.join([word[i:i + 3] for i in range(0, len(word), 3)])

在这种情况下,我得到结果:'364 000 0'

但我需要得到:“3 640 000”

我该如何解决这个任务?

我尝试过类似的方法,但如果一个单词不能被 3 整除而没有余数,那么它对我不起作用

list1 = []
for i in range(len(word) - 1, -1, -3):
print(word[i-2:i+1])
list1.append(word[i-2:i+1])
list1.reverse()

最佳答案

这有点hacky,我们可以使用Python的字符串格式来进行分组,然后替换分隔符(Python只允许“,”和“_”作为分组字符)。

>>> w = '3640000'
>>> f'{int(w):,d}'.replace(',', ' ')
'3 640 000'

关于python - Python 中从字符串末尾开始按 N 个符号分割字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70233822/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com