Home > Back-end >  Is there a way to replace the end of a string, starting at a given substring
Is there a way to replace the end of a string, starting at a given substring

Time:03-13

I have the string banana | 10 and want to replace everything from | to the end of the string with 9. The output I want would be banana | 9. How could I achieve this? I've looked into .replace(), .split() and converting the string into a list of characters, and looping over them until I find the bit that should be replaced, but just couldn't figure it out.

CodePudding user response:

I suggest you use re module(regex module):

import re
myString = "banana | 10"
re.sub(r"\|. ", r"| 9", myString)

Output

banana | 9

CodePudding user response:

Maybe this can work. Code:

string = 'banana | 10 ';
pos = string.find('|')
left_string = string[:pos 2];
final_string = left_string   '9'
print(final_string)

CodePudding user response:

yourStr = 'banana | 10'
yourStr = yourStr[:yourStr.index('|')   2]   '9'
print(yourStr)

banana | 9

The other regex solutions are more elegant, but this is more readable. You can decide what better suits you.

CodePudding user response:

You can capture | followed by optional spaces without a newline in group 1, and match the rest of the line that is to be removed.

In the replacement use capture group 1 followed by 9

import re

s = "banana | 10"
pattern = r"(\|[^\S\n]*).*"
print(re.sub(pattern, r"\g<1>9", s))

Output

banana | 9

If you want to match digits and at least 1 or more spaces, then use:

(\|[^\S\n] )\d 

See a regex 101 demo

CodePudding user response:

You may want to use split() method... This would be helpful for you to understand the method.

sep = ' | '
new_value = 9
s ='banana | 10'.split(sep=sep)
print( s[0]   sep   str(new_value))

CodePudding user response:

The logic can probably be improved but something like this might work:

text = "banana | 10"

if "|" in text:
   tmp = text.split("|")
   print (tmp[0]   "| 9")
  • Related