2

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 2

2

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"
Sign up to request clarification or add additional context in comments.

1 Comment

wow exactly what I was looking for . Cheers ! Regex is amazing .
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.