Issue
var1 = '475 Amsterdam AveNew York, NY 10024'
var2 = '475 Amsterdam Ave'
I want to get "New York, NY 10024"
from var1
I tried:
var3 = var1 - var2
print(var3)
But it is not working.
Can anyone help me with this? Thanks.
Solution
You could use either find()
with string slicing
or replace()
as pointed by Iain based on your requirements:
Scenario 1: When var1
contains a single occurrence of var2
:
Implementation with both find()
with slicing
and replace()
:
var1 = '475 Amsterdam AveNew York, NY 10024'
var2 = '475 Amsterdam Ave'
idx = var1.find(var2)
res = var1[idx+len(var2):] if idx >= 0 else var1
print(res)
res = var1.replace(var2, '')
print(res)
Output: Here both produce produce the same output
New York, NY 10024
New York, NY 10024
Scenario 2: When var2
contains multiple occurrences of var1
:
Implementation with both find()
with slicing
and replace()
:
var1 = '475 Amsterdam AveNew York, NY 10024 475 Amsterdam Ave' # note that var1 has two occurrences of var2
var2 = '475 Amsterdam Ave'
idx = var1.find(var2)
res = var1[idx+len(var2):] if idx >= 0 else var1
print(res)
res = var1.replace(var2, '')
print(res)
Output: Here both produce a different object
New York, NY 10024 475 Amsterdam Ave
New York, NY 10024
Based on the above examples, you could use either of find()
with slicing
or replace()
based on your output requirements.
Answered By - Krishna Chaurasia
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.