1

I have a list

nums = ['Aero', 'Base Core Newton', 'Node']

I want to replace the string Base with Fine i.e Fine Core , i tried the below code, but it dint work

nums = ['Aero', 'Base Core Newton', 'Node']
nums1=[]
for i in nums:
    if 'Base' in i:
        i.replace('Base','Fine')
        nums1.append(i)

print(nums1)

How can i make this work

2
  • Try nums1.append(i.replace('Base','Fine')) Commented May 17, 2018 at 16:23
  • This works however we need to have else to complete this or else only the Fine Core Newton is appended to the list Commented May 17, 2018 at 16:30

2 Answers 2

3

You can use re.sub in a list comprehension. That way, it will be simpler to handle multiple occurrences of 'Base Core' in any elements in nums:

import re
nums = ['Aero', 'Base Core Newton', 'Node']
new_nums = [re.sub('^Base(?=\sCore)', 'Fine', i) for i in nums]

Output:

['Aero', 'Fine Core Newton', 'Node']

regex explanation:

^ -> start of line anchor, anything proceeding must be at the start of the string
Base -> matches the "Base" in the string
?= -> positive lookahead, ^Base will not be matched unless the following pattern in parenthesis is found after ^Base
\sCore -> matches a single space, and then an occurrence of "Core"
Sign up to request clarification or add additional context in comments.

1 Comment

This works, can you please explain a bit more about this
0

I don't think you need to drag re into this. If we use the OP's substitution logic with @Ajax1234's loop structure we get:

nums = ['Aero', 'Base Core Newton', 'Node']
new_nums = [i.replace('Base','Fine') for i in nums]

RESULT

['Aero', 'Fine Core Newton', 'Node']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.