简体   繁体   English

从字符串中删除大写字母

[英]remove the capitalized letters from the string

I have to remove the capitalized letters from the string given我必须从给定的字符串中删除大写字母

When I try to remove the capital letters from the given string, the return function exists at the end of the function which I wrote to print the output causes to the last character to get printed.当我尝试从给定的字符串中删除大写字母时,返回函数存在于我为打印输出而编写的函数的末尾,导致最后一个字符被打印。 Is there any better way to solve it?有没有更好的方法来解决它?

def remove_capitals(a):    
    for i in a:    
          if ord(i)>64 and ord(i)<91:   
               pass  
          else:  
               print(i,end='')  
     return i

print(remove_capitals("A1H5J3ETD"))

expected : 153 actual : 153D预期:153 实际:153D

You print inside and print the return - you return the last i without test .. which is the last letter of your input.您在里面打印并打印返回 - 您返回最后一个i没有测试 .. 这是您输入的最后一个字母。

Modifications:修改:

  • Instead of checking ordinals and magic numbers, use built in fuction isupper() to decide.使用内置的函数isupper()来决定,而不是检查序数和幻数。

  • do not use pass - simply do only something if it is ok to do so不要使用pass - 只需做一些可以的事情

  • collect all parts into a list and join() them back into a string将所有部分收集到一个列表中并将它们join()回一个字符串

Fix:使固定:

def remove_capitals(a):    
    non_upper = []
    for i in a:    
        if not i.isupper():  
            non_upper.append(i)

    return ''.join(non_upper)


print(remove_capitals("A1H5J3ETD"))

Output:输出:

153

You can also append to strings - but strings are immutable so it destroyes the old one and creates a new longer version - which is wasteful:您还可以附加到字符串 - 但字符串是不可变的,因此它会破坏旧的并创建一个新的更长的版本 - 这很浪费:

def remove_capitals(a):    
    non_upper = "" 
    for i in a:    
        if not i.isupper():  
            non_upper += i

    return non_upper

The only benefit this has, is that it does not use lists - it is slower and more memory intensive.这样做的唯一好处是它不使用列表 - 它更慢且占用更多内存。

Use list comprehension使用列表理解

def remove_capitals(a):
    return ''.join([x for x in a if ord(x)<64 or ord(x)>91]))

The last unwanted character is returned because of the return i statement at the end of your function.由于函数末尾的 return i 语句,返回最后一个不需要的字符。 If you just want to print out the non-capitalised letters putting return None and just calling the function (not doing print(remove_capitals("A1H5J3ETD")) : remove_capitals("A1H5J3ETD") should do the trick.如果您只想打印出非大写字母,然后返回 None 并仅调用函数(不执行 print(remove_capitals("A1H5J3ETD")) : remove_capitals("A1H5J3ETD") 应该可以解决问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM