gpt4 book ai didi

Python:字符串中用户定义的数字格式

转载 作者:太空宇宙 更新时间:2023-11-03 16:19:18 25 4
gpt4 key购买 nike

可能是一个已经被问过的问题:如何以用户定义的格式打印整数。

例如

input = 123456
print(".....".format(input))

输出应该是:

"ab123.45.6"

不幸的是,字符串格式的切片是不可能的。所以类似:

"ab{0[:2]}.{0[3:4]}.{0[5]}".format(str(input))

行不通。但有没有比以下更好的解决方案:

"ab{0[0]}{0[1]}{0[2]}.{0[3]}{0[4]}.{0[5]}".format(str(input))

最佳答案

为什么不使用切片 format() 参数?看起来干净一点。

user_input = str(123456)
print("ab{0}.{1}.{2}".format(user_input[:3], user_input[3:5], user_input[5]))

关于Python:字符串中用户定义的数字格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38653134/

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