Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/visual-studio/8.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 3.x 如何从字符串中获取特定的子字符串并用python中的新内容替换该子字符串_Python 3.x - Fatal编程技术网

Python 3.x 如何从字符串中获取特定的子字符串并用python中的新内容替换该子字符串

Python 3.x 如何从字符串中获取特定的子字符串并用python中的新内容替换该子字符串,python-3.x,Python 3.x,嗨,我对Python比较陌生,一直在尝试不同的解决方案,但是找不到任何简单的方法来实现这一点 我有一个字符串,看起来像这样: str='-host hostname-port portnum-app appname-l licensename-service sname' 我只想提取-l licensename,其中许可证名称可能因应用程序而异,并将其替换为-l newlicensename 我尝试过使用replace,但不适合我的需要,因为不同的应用程序使用不同的许可证名称,所以无法批量使用

嗨,我对Python比较陌生,一直在尝试不同的解决方案,但是找不到任何简单的方法来实现这一点

我有一个字符串,看起来像这样:

str='-host hostname-port portnum-app appname-l licensename-service sname'
我只想提取
-l licensename
,其中许可证名称可能因应用程序而异,并将其替换为
-l newlicensename

我尝试过使用replace,但不适合我的需要,因为不同的应用程序使用不同的许可证名称,所以无法批量使用

我尝试的另一个选项是使用join和zip函数,如下所示:

output=[''.join((first,second))用于zip中的first,second(words,secondwords)]
但是,要在列表中仅单独选择字符串的前两部分,这并不如输出那样有效:

[u'-host hostname',u'-hostname-port',u'-port portnum',u'portnum-app',u'-appname',u'appname-service',u'-service sname',u'-l license name',u'sname-l']
而不是预期的:

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

有没有关于最好的方法的建议

您可以使用内置的regex包来执行此操作

首先,我们将创建一个模式,并用新值替换匹配的模式

import re

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

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

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

下面是一个使用字符串解析和数组逻辑的方法。如果您是编程新手,正则表达式可能会让人非常困惑,并且有助于培养数组技能

command_string='-主机主机名-端口端口号-应用程序appname-l licensename-服务sname'
#拆分到空格上的列表
commands=command\u string.split()
#找到“-l”命令的索引,许可证将成为下一个元素
许可证索引=命令索引(“-l”)+1
#更换许可证
命令[license\u index]=“newlicensename”
#将命令重新连接到字符串
新建_命令_字符串=”“.join(命令)
打印(命令字符串)
打印(新命令字符串)
输出
-主机名-端口端口号-应用程序appname-l licensename-服务sname
-主机名-端口端口号-应用程序appname-l newlicensename-服务sname

哇,这正是我想要的。干杯Regex非常棒。