How to grab a specific substring from a string and replace the substring with something new in python

Viewed 39

Hi I am relatively new to Python and have been trying different solutions , however cannot find any easy way to do this.

So I have a string which looks like this:

str = '-host hostname -port portnum -app appname -l licensename -service sname'

I want only to extract the -l licensename where license name could be different depending on apps and replace this with -l newlicensename.

I tried using replace, but wont suit my needs as different apps use different license names so cannot do for bulk.

Another option I tried was to use join and zip functions like below:

output = [' '.join((first, second)) for first, second in zip(words, secondwords)]

to select only the first two sections of the string separately in a list, however, this did not work as well as the output was:

[u'-host hostname', u'hostname -port', u'-port portnum', u'portnum -app', u'-app appname', u'appname -service', u'-service sname', u'-l licencename , 'u'sname -l']

instead of the expected:

['-host hostname', '-port portnum', '-app appname', '-l licencename','-service sname']

Any suggestions on the best way to do this?

2 Answers

You can use the inbuilt regex package to do this

First, we will create a pattern and replace the matching pattern with the new value.

import re

s = '-host hostname -port portnum -app appname -l licensename -service sname'
pattern = r'-l [\w]+'

s = re.sub(pattern, '-l newlicensename', s)

Output

Old: "-host hostname -port portnum -app appname -l licensename -service sname"
New: "-host hostname -port portnum -app appname -l newlicensename -service sname"

Here's a method that uses string parsing and array logic. If you're new to programming, regular expressions can be very confusing, and it's good to build array skills.

command_string = '-host hostname -port portnum -app appname -l licensename -service sname'

# Split to list on spaces
commands = command_string.split()

# Find the index of the "-l" command, the license will be the next element
license_index = commands.index("-l") + 1

# Replace the license
commands[license_index] = "newlicensename"

# Join the command back to a string
new_command_string = " ".join(commands)

print(command_string)
print(new_command_string)

Output

-host hostname -port portnum -app appname -l licensename -service sname
-host hostname -port portnum -app appname -l newlicensename -service sname
Related