假设我有一个 IBAN:NL20INGB0001234567
如何将除最后 4 位以外的所有数字更改为*
:
Input: NL20INGB0001234567
Output: NL20INGB******4567
除 NL*20* 以外的所有数字
使用regex
:
>>> import re
>>> strs = 'NL20INGB0001234567'
>>> re.sub(r'(\d+)(?=\d{4}$)', lambda m:'*'*len(m.group(1)), strs)
'NL20INGB******4567'
最简单的?
import re
s='NL20INGB0001234567'
re.sub(r'\d+(\d{4})$',r'****\1',s)
结果:
'NL20INGB****4567'
>>> iban = "NL20INGB0001234567"
>>> iban[:4] + ''.join(i if i.isalpha() else "*" for i in iban[4:-4]) + iban[-4:]
'NL20INGB******4567'
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
tmp = ''
iban = 'NL20INGB0001234567'
for i in iban[4:-4]:
if i.isdigit():
tmp += '*'
else:
tmp += i
iban = iban[:4] + tmp + iban[-4:]
根据您提出问题的方式,我假设您要格式化一个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
理解?
快乐编码!