将部分字符串更改为*

时间:2013-11-13 16:56:21

标签: python string

假设我有一个IBAN:NL20INGB0001234567

如何将除最后4位以外的所有数字更改为*

Input: NL20INGB0001234567
Output: NL20INGB******4567

所有数字,但NL * 20 *

6 个答案:

答案 0 :(得分:5)

使用regex

>>> import re
>>> strs = 'NL20INGB0001234567'
>>> re.sub(r'(\d+)(?=\d{4}$)', lambda m:'*'*len(m.group(1)), strs)
'NL20INGB******4567'

答案 1 :(得分:1)

最简单?

import re
s='NL20INGB0001234567'
re.sub(r'\d+(\d{4})$',r'****\1',s)

结果:

'NL20INGB****4567'

答案 2 :(得分:0)

tmp = ''
iban = 'NL20INGB0001234567'
for i in iban[4:-4]:
     if i.isdigit():
             tmp += '*'
     else:
             tmp += i

iban = iban[:4] + tmp + iban[-4:]

答案 3 :(得分:0)

>>> iban = "NL20INGB0001234567"
>>> iban[:4] + ''.join(i if i.isalpha() else "*" for i in iban[4:-4]) + iban[-4:]
'NL20INGB******4567'

答案 4 :(得分:0)

s = "IBAN: NL20INGB0001234567"

s = [ele for ele in s.split(':')[-1] if ele.strip()]

mask = [1 for ele in range(len(s) - 10)] + [0] * 6 + [1] * 4

print ''.join(["*" if mask[i] == 0 else ele for i, ele in enumerate(s)])

输出:

NL20INGB******4567

答案 5 :(得分:0)

根据您提出问题的方式,我假设您要格式化IBAN字符串

##################

########******####

基于此,一个简单的解决方案就是编写这个函数:

def ConverterFunction(IBAN):
    return IBAN[:8]+"******"+IBAN[14:]

并用这一行调用它:

ConverterFunction(<your IBAN here>)

当然,在必要时附加作业或prints

编辑:也可能需要一些解释。

无论你使用什么IBAN都是一个字符串,字符串可以是sliced。通过切片,一个人可以拾取一部分字符串并留下其他人。它使用每个字母的位置索引,如下所示:

This is OK
0123456789

注意,索引始终从0开始,而不是1

获取字符串切片的示例:

examplestring = "EXAMPLE!"
print examplestring[:3] # "[:3]" means "from beginning to position 3"
print examplestring[5:] # "[5:]" means "from position 5 to end of string"
print examplestring[3:5] # "[3:5]" means "from position 3 to position 5"

输出:

>> EXAM
>> LE!
>> MPL

所以在我的解决方案中,函数ConverterFunction(IBAN)的作用是:

#Takes string "IBAN"
#Chops off the beginning and end parts you want to save
#Puts them back together with "******" in the middle

明白了吗?

快乐的编码!