简体   繁体   中英

How to replace next word after a specific word in python

I have a string like below. Here, I want to replace just next immediate word after a particular word like, '%(db_user)s' and '%(db_passsword)s' but the words I can search for in the string are --db-user and --db-passwords becuase the above will be substituted by values.

Input:

 "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' "

Output:

 "cd scripts &&   bash setup.sh  --client-name %(client_name)s --is-db-auth-enabled %(is_db_auth_enabled)s --db-user '***' --db-password '****' "

So please help me with a function where I will provide an array of words and a string, which will replace next words to those supplied words.

This will help -

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))

You could use insert here. You would .split() your intial string to make it a list . Then you would insert into the position one after the index of the word you are searching. After ' '.join() the list back into a string .

s = "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' "

s = s.split()
a = '***'
b = '****'

s.insert((s.index('--db-user')+1), a)
s.insert((s.index('--db-password')+1), b)
s = ' '.join(s)
print(s)
# 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'

a function where I will provide an array of words and a string, which will replace next words to those supplied words.

Using general string processing

The following solution leverages Python's list.index method which is great to find stuff in well-formatted strings, short of using regexp.

def replace_cmdargs(cmdargs, argmap):
   words = cmdargs.split(' ')
   for arg, value in argmap.iteritems():
      index = words.index(arg)
      argname = words[index + 1].replace('%(', '').replace(')s', '').replace("'", '').replace('"', '')
      words[index + 1] = words[index + 1] % {argname: value}
   return ' '.join(words)

This works by first splitting the input string into words, then for each key/value pair in argmap find the index of the key and replace the existing word at index + 1 by the respective value.

We can use the replace_cmdargs function as follows

cmdargs = "--db-user '%(db_user)s' --db-password '%(db_password)s'"
replace_cmdargs(cmdargs, {
        '--db-user': 'MYUSER',
        '--db-password': 'MYPASS'
    })

=> "--db-user 'MYUSER' --db-password 'MYPASS'"

Note: This assumes the string is well-formatted, ie there is only one space between the key and the value to be replaced and there is always a corresponding string value.

Leveraging Python's built-in string formatting

Since we already have a well-formatted string with format instructions in it, we could of course also use Python's built-in string formatting operator, no extra function needed:

cmdargs % { 'db_user': 'MYUSER', 'db_password': 'MYPASS'}
=> "--db-user 'MYUSER' --db-password 'MYPASS'"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM