在字符串中每 3 个字符后插入句点 [英] inserting period after every 3 chars in a string

查看:45
本文介绍了在字符串中每 3 个字符后插入句点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个:

from __future__ import print_functiondef f_comma(p_string):v_string = p_stringif (type(v_string) == type(int()) 或 type(v_string) == type(long()) 或type(v_string) == type(float())):v_string = str(v_string)别的:l_string = 列表(v_string)对于范围内的 v_index(3, len(l_string), 4):l_string.insert(v_index, ',')v_result = ''.join(l_string)返回(v_result)打印 (f_comma('qwertyuiopaq'))

似乎我无法弄清楚为什么如果我使用长度超过 11 个字符的字符串,句点会停止插入,但只有 11 个字符它工作正常.我在这篇文章中做错了什么?

解决方案

您可以像这样在每第 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'

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. What i'm doing wrong in this piece?

解决方案

You can insert a comma after every nth character like this:

>>> 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.

>>> 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'

这篇关于在字符串中每 3 个字符后插入句点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆