我正在尝试编写代码来查找包含特殊字符,数字和字母的字符串中的字母。以下代码不返回任何内容:
a ="&*&)*&GOKJHOHGOUIGougyY^&*^x".lower()
print(a)
final = a.split()
for y in final:
if (y.isalpha == True):
print(y)
输出:&&)&gokjhohgouigougugyy ^&* ^ x =>无
有人可以告诉我问题出在哪里,而不使用怎么办re.findall
,例如使用如下循环:
for(y in final):
if (ord(y) in range (97, 127)):
print(y)
上面的代码有效:
for y in a:
if (ord(y) in range (97, 127)):
print(y, end='')
你需要调用y.isalpha
的y.isalpha()
,这是因为因而isalpha是一个函数或方法。
>>> y='y'
>>> y.isalpha
<built-in method isalpha of str object at 0x00FA3A40>
>>> y.isalpha()
True
请注意,拆分后的单词不会是字母-可能不是您所期望的:
>>> s = "Yes! These are words."
>>> for w in s.split(' '):
... print(w, w.isalpha())
...
Yes! False
These True
are True
words. False
>>>
在python中要习惯的一件事是属性和方法之间的区别-属性是您可以读取方法执行某些操作的东西-dir
列出两者以便为s
您提供一个字符串:
>>> dir(s)
['__add__', '__class__', '__contains__', '__delattr__', '__dir__',
'__doc__', '__eq__', '__format__', '__ge__', '__getattribute__',
'__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__',
'__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__',
'__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__',
'__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__',
'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith',
'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum',
'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower',
'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join',
'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind',
'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines',
'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill'
]
在哪里:
>>> s.__class__
<class 'str'>
是一个属性,并且:
>>> s.capitalize
<built-in method capitalize of str object at 0x03529F50>
是一种方法,需要通过添加括号()来调用以实际执行其功能。还值得在返回值的方法和在适当位置操作的方法之间进行区分。
>>> s.lower()
'yes! these are words.'
返回一个值,s.split()
但它sort
是就地操作,例如:
>>> words = s.lower().split()
>>> words
['yes!', 'these', 'are', 'words.']
>>> words.sort()
>>> words
['are', 'these', 'words.', 'yes!']
>>>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句