将char插入字符串至数字末尾 [英] Insert char to string to end of number

查看:215
本文介绍了将char插入字符串至数字末尾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的字符串很丑:

oldstr = "0.100% fDrg: 2%,dgdv: 29% fGd dg 0.2%, Ghh-sf 2.2 dbgh: NONE dfgdf6 gd 3 "

需要在此数字的最后一位之后插入char |,以便通过此插入的|进行下一次拆分.还有一个值none,还在其中添加了此分隔符:

I need to insert char | after the last digit of number for next splitting by this inserted |. There is also value none, where is also added this separator:

0.100| fdrg: 2|,dgdv: 29| fgd dg 0.2|, ghh-sf 2.2|dbgh: none| dfgdf6|gd 3|

尝试,但没有成功:

print re.sub(r'(\d+[a-z %^.])', r'\1|', oldstr.lower())

0.|100%| fdrg: 2%|,dgdv: 29%| fgd dg 0.|2%|, ghh-sf 2.|2 |dbgh: none dfgdf6 |gd 3 |

任何帮助将不胜感激.

推荐答案

您可以使用

(\bnone\b|\d+(?:\.\d+)?)%?

并替换为\1|.

说明:

  • (\bnone\b|\d+(?:\.\d+)?)-组1匹配2个替代方案:
    • \bnone\b-整个词none
    • |-或...
    • \d+(?:\.\d+)?-浮点值(\d+匹配一个或多个数字,而(?:\.\d+)?匹配(可选)一个点后跟一个或多个数字)
    • (\bnone\b|\d+(?:\.\d+)?) - Group 1 matching 2 alternatives:
      • \bnone\b - whole word none
      • | - or...
      • \d+(?:\.\d+)? - a float value (\d+ matches one or more digits, and (?:\.\d+)? matches (optionally) a dot followed with one or more digits)

      请参见 regex演示

      Python代码:

      import re
      p = re.compile(ur'(\bnone\b|\d+(?:\.\d+)?)%?', re.IGNORECASE)
      test_str = "0.100% fDrg: 2%,dgdv: 29% fGd dg 0.2%, Ghh-sf 2.2 dbgh: NONE dfgdf6 gd 3 "
      subst = "\1|"
      result = re.sub(p, subst, test_str)
      

      如果需要修整值,则可以在拆分后进行修整.另外,在使用re.sub(r'\b\none\b', 'NONE', input)处理文本之前,可以将none变为小写.

      If you need to trim the values, you will be able to do it after splitting. Also, none can be turned lower case before processing the text with re.sub(r'\b\none\b', 'NONE', input).

      这篇关于将char插入字符串至数字末尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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