Python 在字符串中每3个字符后插入句点
我有这个:Python 在字符串中每3个字符后插入句点,python,python-2.7,Python,Python 2.7,我有这个: from __future__ import print_function def f_comma(p_string): v_string = p_string if (type(v_string) == type(int()) or type(v_string) == type(long()) or type(v_string) == type(float())): v_string = str(v_string) else:
from __future__ import print_function
def f_comma(p_string):
v_string = p_string
if (type(v_string) == type(int()) or type(v_string) == type(long()) or
type(v_string) == type(float())):
v_string = str(v_string)
else:
l_string = list(v_string)
for v_index in range(3, len(l_string), 4):
l_string.insert(v_index, ',')
v_result = ''.join(l_string)
return (v_result)
print (f_comma('qwertyuiopaq'))
似乎我不明白为什么如果我使用长度超过11个字符的字符串,句点就会停止插入,但只有11个字符,它就可以正常工作。我在这篇文章中做错了什么?以下是它不起作用的原因。(而不是像其他人所展示的那样,解决你效率低下的方法。) 当您
.insert()
将某些内容插入列表时,每个元素都会向前移动一个位置以腾出空间
您先前使用
范围(3,len(l_字符串),4)计算的索引将不再是您想要的索引。您可以在每n个字符后插入逗号,如下所示:
>>> my_str = 'qwertyuiopaq'
>>> ','.join(my_str[i:i+3] for i in range(0, len(my_str), 3))
'qwe,rty,uio,paq'
这也适用于任意长度的字符串
编辑:以与@mhawke的答案类似的样式作为函数编写,带有更改分组/字符的选项
>>> def f_comma(my_str, group=3, char=','):
... my_str = str(my_str)
... return char.join(my_str[i:i+group] for i in range(0, len(my_str), group))
...
>>> f_comma('qwertyuiopaq')
'qwe,rty,uio,paq'
>>> f_comma('qwertyuiopaq', group=2)
'qw,er,ty,ui,op,aq'
>>> f_comma('qwertyuiopaq', group=2, char='.')
'qw.er.ty.ui.op.aq'
下面是使用切片的另一种方法:
def f_comma(p_string, n=3):
return ','.join(p_string[i:i+n] for i in range(0, len(p_string), n))
我认为没有必要在你的版本中进行类型检查。您的代码检查int、long或float的实例,然后将其中任何一个转换为字符串。您只需转换为字符串,无需检查类型:
def f_comma(p_string, n=3):
p_string = str(p_string)
return ','.join(p_string[i:i+n] for i in range(0, len(p_string), n))
>>> f_comma('abcdefghijklmnop')
'abc,def,ghi,jkl,mno,p'
>>> f_comma(1234567890)
'123,456,789,0'
>>> import math
>>> f_comma(math.pi)
'3.1,415,926,535,9'
现在,这不会处理所有unicode字符串:
>>> f_comma(u'abcdefg\u3030\u3031\u3032\u3033')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in f_comma
UnicodeEncodeError: 'ascii' codec can't encode characters in position 7-10: ordinal not in range(128)
另请注意,使用默认参数指定线段长度:
>>> f_comma('abcdefghijklmnop')
u'abc,def,ghi,jkl,mno,p'
>>> f_comma('abcdefghijklmnop', 6)
u'abcdef,ghijkl,mnop'
你能举一个输出失败的例子吗?你的函数不起作用,因为你没有考虑到先前插入的额外逗号。例如,当字符串的长度为100时,您必须在字符串之间加上33个逗号,但Python2中的range
函数没有考虑到这一点。不,仍然不起作用。试试打印(用逗号('qwertyuiopaqwertyuiopaqwertyuiopaqqwertyuiopaqwertyuiopaq'))
@Nitzle比你快了几秒钟@伦敦罗布:是的。。。而且,这似乎对提高投票率产生了巨大的影响!:)很抱歉我不该提起这件事。不过,@Nitzle比你更需要代言人f_逗号(12345)
=>TypeError:type'int'的对象没有len()
。OP的代码显示了支持非字符串参数(如int、long和float)的努力。@mhawke:good point,使用str()
更新了转换函数。挑剔,但unicode字符串如何,例如f_逗号(u'Caf')
是的,OP是否关心unicode字符串还不清楚,但说到你的观点,如果这是一个问题,OP可以轻松地使用unicode()
函数,而不是回答中所示的str()
。@udarH3:您可以使用列表理解而不是生成器表达式,但可能没有理由这样做(除非您有非常长的字符串)<代码>[my_str[i:i+组]用于范围内的i(0,len(my_str),组)]
>>> f_comma('abcdefghijklmnop')
u'abc,def,ghi,jkl,mno,p'
>>> f_comma('abcdefghijklmnop', 6)
u'abcdef,ghijkl,mnop'