简体   繁体   中英

remove substring from string using python

I would like to remove 2 last sub-strings from a string like the following example :

str="Dev.TTT.roker.{i}.ridge.{i}."

str1="Dev.TTT.roker.{i}.ridge.{i}.obj."

if in the last two strings between the dot . there is a {i} we have to remove it as well. so the result of python script should be loke this :

the expected result for str is : Dev.TTT.

the expected result for str1 is : Dev.TTT.roker.{i}.

  • you can simply split by . and ignore empty string or {i} .
  • Also do not use keyword as variable. In your case dont use str as variable name.
def solve(s):
    x = s.split('.')
    cnt = 2
    l = len(x) - 1
    while cnt and l:
        if x[l] == '' or x[l] == '{i}':
            l -= 1
            continue
        else:
            cnt -= 1
            l -= 1
    return '.'.join(x[:l+1]) + '.'

str1="Dev.TTT.roker.{i}.ridge.{i}."

str2="Dev.TTT.roker.{i}.ridge.{i}.obj."

print(solve(str1))
print(solve(str2))

output:

Dev.TTT.
Dev.TTT.roker.{i}.

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