简体   繁体   中英

deleting specific word in python

I have practice question which I struggled with I'm gonna put the question and the code I tried Thanks all(Im new)

Given a string, return a new string where "not " has been added to the front. However, if the string already begins with "not", return the string unchanged.

MY code:

def not_string(str):
  return 'not' + ' ' +  str
  if str == 'not' :
    return str

Here is a possible piece of code:

def not_string(s):
    if s.startswith('not'):
        return s
    return 'not ' + s

You can also use a one liner:

def not_string(s):
    return s if s.startswith('not') else 'not ' + s

If you do not want to use built-in functions then you might want to try something like this:

def not_string(s):
    if s[:3] == 'not':
        return s
    return 'not ' + s

Your code have return in the first line of the function, so the rest is never reached. The first line just returns "not" and your string. The second line just checks if the string is "not" ( star == 'not' ) and not check if it starts with "not".

My solution:

def not_string(str):
  if str.startswith("not"):
    return str
  return "not " + str

First check if start with "not" in the input string

if have, just return it

if not it will return the "not" with the input string

The order of the sentences in your code is important. The first line in the not_string function is a return statement. As soon as the interpreter execute this order, it exits the function and returns (hence the name) to the caller code. This means the rest of the lines if the function are never executed.

One solution is to invert the order ot the things you are doing in the function: first check if the string needs to be modified (that is to say, it doesn't starts with not ). If this is the case, add the not at the start of the string. Final step is returning the value:

def not_string(str):
    if not str.startswith('not '):
        str = 'not ' + str
    return str

Note: Concatenating strings with + is the least efficent way to do it, but do not care about this for now.

def not_string(s): 如果 s.startswith('not') else 'not ' + s,则返回 s

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