Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/349.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将字符串的一部分更改为*_Python_String - Fatal编程技术网

Python 将字符串的一部分更改为*

Python 将字符串的一部分更改为*,python,string,Python,String,假设我有一个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

假设我有一个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'
输出:

NL20INGB******4567
>> EXAM
>> LE!
>> MPL

根据您对问题的措辞方式,我假设您希望格式化来自的
IBAN
字符串

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

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

def ConverterFunction(IBAN):
    return IBAN[:8]+"******"+IBAN[14:]
用这句话来称呼它:

ConverterFunction(<your IBAN here>)
注意,索引总是从
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"
输出:

NL20INGB******4567
>> 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
明白吗


快乐编码

除NL20外的所有数字??确切地说,除NL20外的所有数字都是固定长度的IBAN,其中您要转换为
***
的数字始终分别在第9位和第14位开始和结束?您的意思是只转换尾随数字?是的,只有尾随数字在您脚下编辑问题时很难。。!很明显,这只会像最初发布的那样放置4颗星,而不是数字的确切数字。如果长度始终相同,则可以更改
*
的数量。正则表达式很少是“最简单的”。。。但是是的,这应该很好…@JoranBeasley是的,我可能应该说“这似乎比其他假设的答案更简单”。旧的“”情况…基于长度的解决方案而不是基于上下文的解决方案的问题是IBAN的长度可能为16-30个字符…如果我们上面的朋友必须这样做,则基于长度的解决方案可以继续使用负索引来保存字符串的最后四个字母,而不考虑中间内容,虽然我明白你的意思。我考虑过负指数,但假设开头的字母数相同,只有位数不同。显然,OP要求在任何情况下都要得到更好的定义!我试着用海报来保证所有这些条件。我的回答基于这些条件,并向我们保证这一点。
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
#Takes string "IBAN"
#Chops off the beginning and end parts you want to save
#Puts them back together with "******" in the middle