我有2个字符串a
和b
,以-
作为分隔符,想通过将子字符串连接到%
的最后一个a
来获得第三个字符串(在下面的示例中为one-two-three-%whatever%
,并从字符串b
中删除子字符串,直到在结果字符串中找到破折号(在下面为4,例如,得到bar-bazz
),我做了到目前为止,有没有更好的方法?
>>> a='one-two-three-%whatever%-foo-bar'
>>> b='1one-2two-3three-4four-bar-bazz'
>>> k="%".join(a.split('%')[:-1]) + '%-'
>>> k
'one-two-three-%whatever%-'
>>> k.count('-')
4
>>> y=b.split("-",k.count('-'))[-1]
>>> y
'bar-bazz'
>>> k+y
'one-two-three-%whatever%-bar-bazz'
>>>
答案 0 :(得分:0)
使用正则表达式的另一种方法:
import re
a = 'one-two-three-%whatever%-foo-bar'
b = '1one-2two-3three-4four-bar-bazz'
part1 = re.findall(r".*%-",a)[0] # one-two-three-%whatever%-
num = part1.count("-") # 4
part2 = re.findall(r"\w+",b) # ['1one', '2two', '3three', '4four', 'bar', 'bazz']
part2 = '-'.join(part2[num:]) # bar-bazz
print(part1+part2) # one-two-three-%whatever%-bar-bazz
答案 1 :(得分:0)
对于从a
获得的第一个子字符串,可以使用rsplit()
:
k = a.rsplit('%', 1)[0] + '%-'
其余的对我来说很好
答案 2 :(得分:0)
也许短一点?
a = 'one-two-three-%whatever%-foo-bar'
b = '1one-2two-3three-4four-bar-bazz'
def merge (a,b):
res = a[:a.rfind ('%')+1]+'-'
return (res + "-".join (b.split ("-")[res.count ('-'):]))
print (merge (a,b) == 'one-two-three-%whatever%-bar-bazz')
答案 3 :(得分:0)
当我需要手动增加索引或连接裸字符串时,我个人会感到紧张。
这个答案与铰链的答案非常相似,只是没有附加的concat / addition运算符。
t = "-"
ix = list(reversed(a)).index("%")
t.join([s] + b.split(t)[len(a[:-ix].split(t)):])
答案 4 :(得分:0)
另一个可能的答案:
def custom_merge(a, b):
result = []
idx = 0
for x in itertools.zip_longest(a.split('-'), b.split('-')):
result.append(x[idx])
if x[0][0] == '%' == x[0][-1]:
idx = 1
return "-".join(result)
答案 5 :(得分:0)
您的问题足够具体,您可能正在优化错误的内容(较大问题中的一小部分)。话虽这么说,一种易于理解且避免某些重复的线性遍历(拆分,联接和计数)的方法是:
def funky_percent_join(a, b):
split_a = a.split('-')
split_b = b.split('-')
breakpoint = 0 # len(split_a) if all of a should be used on no %
for neg, segment in enumerate(reversed(split_a)):
if '%' in segment:
breakpoint = len(split_a) - neg
break
return '-'.join(split_a[:breakpoint] + split_b[breakpoint:])
然后
>>> funky_percent_join('one-two-three-%whatever%-foo-bar', '1one-2two-3three-4four-bar-bazz')
'one-two-three-%whatever%-bar-bazz'
答案 6 :(得分:0)
print(f"one-two-three-%{''.join(a.split('%')[1])}%")
首先适用,然后您可以对第二个执行相同操作,当您准备好进行连接时,可以执行以下操作:
part1 = str(f"one-two-three-%{''.join(a.split('%')[1])}%")
part2 = str(f"-{''.join(b.split('-')[-2])}-{''.join(b.split('-')[-1])}")
result = part1+part2
这样,只要它们将a / b变量设置为相同格式,它就会抓取您设置的内容。
但是再说一次,为什么不做类似的事情:
result = str(a[:-8] + b[22:])