简体   繁体   中英

Return a string by using if…else in a for loop

so here I am trying to convert the string ' ABcsad f!,' into
string 'abcsadf' , so basically I am trying to replace the space and non-alpha into '' but my code not working at all...

s = ' ABcsad f!,'

def norm(s):
    b=''
    i=0
    for i in range(0,len(s)+1):
        if (s[i].isalpha() is False) or (s[i].isspace() is False) :
            return b+=''
        else:
            return b+=s[i]
        i = i+1   

print(norm(s))

anyone can tell me which part I goes wrong?

Try this :

s = ' ABcsad f!,'
def norm(s):
    return ''.join(i for i in s.lower() if i.isalpha())
print(norm(s))

Output :

'abcsadf'

Here is where you went wrong

  1. You put the return inside the for loop. Return exits the entire norm function rather than allowing the for loop to finish. It needed to be moved outside.

  2. len(s) + 1 causes an out of range error. It should just be len(s)

  3. As you want to remove spaces, s[i].isspace() should be checked for being true.

  4. If you want everything lowercase, you need to make s[i] to s[i].lower()

  5. You can use b += ... but you cannot use it in its own return statement. It is irrelevant anyway as you should not be using return there.

def norm(s):
    b=''
    for i in range(0,len(s)):
        if (s[i].isalpha() is False) or (s[i].isspace() is True):
            b += ""
        else:
            b += s[i].lower()
        i = i+1
    return b

s = ' ABcsad f!,'
print(norm(s))

May be with regex:

import re

mystring = ' ABcsad f!,'
print (re.sub('[^A-Za-z0-9]+', '', mystring)).lower()

Output:

abcsadf

The problem is that, your code has errors because you are trying to return b at an invalid position.

Your code

return b+=''

in python does not work as expected in languages like Java. You have to return b explicitly.

Though its not the best way, just tried to use the same code what you wrote , but in a correct way (not pythonian way ;-))

s = ' ABcsad f!,'

def norm(s):
    b=''
    i=0
    for i in range(0, len(s)):
        if not s[i].isalpha() or s[i].isspace():
            b += ''
        else:
            b += s[i]
        i = i+1
    return b

print(norm(s))

There are more ways like use of regex , replace operations to do this operation more efficiently in python. Hope you get the mistake.

You returned b after the first iteration. No matter what the first character is, you returned b which did not let the loop go through your string. So, you need to keep return b out of loop. And also there is no need to return b+=s[i] . Just return b+s[i] would have been okay. In fact, you can't assign a value in return statement. However, the code can be cut short like the following:

s = ' ABcsad f!,'

def norm(s):
    b=''
    i=0
    for i in range(0, len(s)):
        if s[i].isalpha():
            b+=s[i]
    return b.lower()

print(norm(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