[英]inserting period after every 3 chars in a string
I have this: 我有这个:
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'))
It seems that i can't figure it out why if i use a string longer than 11 chars the period stops inserting, but with only 11 chars it works fine. 似乎我无法弄清楚为什么如果我使用超过11个字符的字符串,句点停止插入,但只有11个字符,它工作正常。 What i'm doing wrong in this piece?
我在这件作品中做错了什么?
You can insert a comma after every nth character like this: 您可以在每个第n个字符后插入一个逗号,如下所示:
>>> my_str = 'qwertyuiopaq'
>>> ','.join(my_str[i:i+3] for i in range(0, len(my_str), 3))
'qwe,rty,uio,paq'
This should work for any arbitrary length of strings too. 这也适用于任意长度的字符串。
Edit: Written as a function in a similar style to @mhawke's answer, with an option to change the grouping/characters. 编辑:以与@ 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'
Here is an alternative way to do it using slicing: 以下是使用切片执行此操作的另一种方法:
def f_comma(p_string, n=3):
return ','.join(p_string[i:i+n] for i in range(0, len(p_string), n))
I don't think that the type checking in your version is necessary. 我不认为您的版本中的类型检查是必要的。 Your code checks for instances of an int, long or float and then converts any of these to a string.
您的代码检查int,long或float的实例,然后将其中任何一个转换为字符串。 You can just convert to a string without checking the type:
您可以在不检查类型的情况下转换为字符串:
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'
Now this won't handle all unicode strings: 现在这不会处理所有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)
Here you can use isinstance()
(preferable to type() ==
) to aid conversion of non-string types: 在这里你可以使用
isinstance()
(最好是type() ==
)来帮助转换非字符串类型:
def f_comma(p_string, n=3):
if not isinstance(p_string, basestring): # str or unicode
p_string = str(p_string) # convert only non-strings
return ','.join(p_string[i:i+n] for i in range(0, len(p_string), n))
>>> f_comma(u'abcdefg\u3030\u3031\u3032\u3033') # returns unicode
u'abc,def,g\u3030\u3031,\u3032\u3033'
>>> f_comma('wowwowwowwow') # returns str
'wow,wow,wow,wow'
>>> f_comma(math.pi) # returns str
'3.1,415,926,535,9'
Also notice the use of a default argument to specify the segment length: 另请注意使用默认参数指定段长度:
>>> f_comma('abcdefghijklmnop')
u'abc,def,ghi,jkl,mno,p'
>>> f_comma('abcdefghijklmnop', 6)
u'abcdef,ghijkl,mnop'
Here's why it doesn't work. 这就是为什么它不起作用。 (Rather than solving your method which is a pretty inefficient one, as others have shown.)
(而不是解决你的方法,这是一个非常低效的方法,正如其他人已经表明的那样。)
When you .insert()
something into your list, every element gets shifted forward a position to make room. 当你将
.insert()
放入列表中时,每个元素都会向前移动一个位置以腾出空间。
The indexes you calculated earlier with range(3, len(l_string), 4)
are then no longer what you want them to be. 之前使用
range(3, len(l_string), 4)
计算的索引不再是您想要的索引。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.