我有一个像下面这样的字符串。在这里,我只想在诸如'%(db_user)s'和'%(db_passsword)s'之类的特定单词之后替换下一个立即数,但是我可以在字符串中搜索的单词是--db-user和- db-passwords,因为以上将被值替换。
输入:
"cd scripts && bash setup.sh --client-name %(client_name)s --is-db-auth-enabled %(is_db_auth_enabled)s --db-user '%(db_user)s' --db-password '%(db_password)s' "
输出:
"cd scripts && bash setup.sh --client-name %(client_name)s --is-db-auth-enabled %(is_db_auth_enabled)s --db-user '***' --db-password '****' "
因此,请为我提供一个函数,该函数将提供一个单词数组和一个字符串,该字符串将替换下一个单词。
这将有助于-
import re
def char_index(sentence, word_index):
sentence = re.split('(\s)',sentence) #Parentheses keep split characters
return len(''.join(sentence[:word_index*2]))
def print_secure_message(msg):
secure_words = ['--db-user', '--db-password']
# Removing extra white spaces within string
msg = re.sub(' +', ' ', msg)
cpy_msg = msg.split(" ")
for word in secure_words:
# Getting index of the word's first characters
t = re.search(word, msg)
# Getting index of the next word of the searched word's
word_index = cpy_msg.index(word)+2;
index= char_index(msg, word_index)
print(t.end(), word_index, index)
msg = msg[0:t.end() + 1] + "'****'" + msg[index - 1:]
print(''.join(msg))
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句