如果字符不是字母,则返回值isalpha()
是,0
如果是字母则返回非零值。许多其他ctype.h
库函数也是如此。
这个函数的返回类型有什么意义吗?
换句话说,为什么不简单地返回1
字母字符呢?
我用谷歌搜索并没有找到任何答案。
我编写了一个实用程序来扫描包含字母字符的所有空格分隔字段的文本文件,它工作得很好但是非常慢,因为我将每行分成单词并扫描每个单词,有更快的方法吗?
谢谢.
这是代码:
#!/bin/python
import argparse
import sys
import time
parser = argparse.ArgumentParser(description='Find all alpha characters in
an input file')
parser.add_argument('file', type=argparse.FileType('r'),
help='filename.txt')
args = parser.parse_args()
def letters(input):
output = []
for character in input:
if character.isalpha():
output = input
return output
def main(argv):
start = time.time()
fname = sys.argv[1]
f = open(fname)
for line in f:
words = line.rstrip().split()
for word in words:
alphaWord = letters(word)
if alphaWord:
print(alphaWord)
f.close()
end = time.time()
elapsed = end - start
print …
Run Code Online (Sandbox Code Playgroud) 我有一个字符串
c=("Snap-on Power M1302A5 Imperial,IMPRL 0.062IN")
Run Code Online (Sandbox Code Playgroud)
我需要将上面的字符串转换为
c=("Snap-on Power Imperial,IMPRL")
Run Code Online (Sandbox Code Playgroud)
即我需要删除同时包含字母和数字的字符串,
我怎么能在python中做到这一点?
我试过
c=c.apply(word_tokenize)
c = c.apply(lambda x: [item for item in x if item.isalpha()])
Run Code Online (Sandbox Code Playgroud)
但得到了输出
c=("Snap-on Power MA Imperial,IMPRL IN")
Run Code Online (Sandbox Code Playgroud) 玩弄isalpha()
,我注意到了一些奇怪的行为。
"a".isalpha()
>>True
"2".isalpha()
>> False
Run Code Online (Sandbox Code Playgroud)
上面的两个语句返回了我期望的结果。但是,现在之前添加波浪号就没有意义了。
~"a".isalpha()
>> -2
~"2".isalpha()
>> -1
Run Code Online (Sandbox Code Playgroud)
为什么会发生这种情况?我发现使用not
而不是~
返回我期望的输出,但我对上述行为感兴趣。
not "a".isalpha()
>> False
not "2".isalpha()
>> True
Run Code Online (Sandbox Code Playgroud) 我编写了一个代码,以便它使用 isalpha() 函数删除除 alphabats 之外的所有内容(如空格和其他内容),并使用 tolower() 函数将其转换为小写。如果我不在字符串中放置空格,它工作正常,但如果字符串中有任何空格,则它超出了空格。我不明白为什么会这样。这是我写的代码。
#include<bits/stdc++.h>
#include<cstring>
#include<cctype>
using namespace std;
int main()
{
int i;
string A,b="";
cin>>A;
for(i=0;i<A.size();i++)
{
if(isalpha(A[i]))
b+= tolower(A[i]);
else
continue;
}
cout<<b;
}
Run Code Online (Sandbox Code Playgroud)
请帮我。谢谢
我正在尝试编写一个简单的代码来检查字符串中是否只有数字。到目前为止它还没有工作,任何帮助将不胜感激。
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main()
{
char numbers[10];
int i, correctNum = 0;
scanf("%s", numbers);
for(i = 0 ; i <= numbers ; ++i)
{
if(isalpha(numbers[i]))
{
correctNum = 1;
break;
}
}
if(correctNum == 1)
{
printf("That number has a char in it. FIX IT.\n");
}
else
{
printf("All numbers. Good.\n");
}
return 0;
}
Run Code Online (Sandbox Code Playgroud) isalpha ×6
c ×2
python ×2
arrays ×1
c++ ×1
char ×1
ctype ×1
preprocessor ×1
python-3.x ×1
tolower ×1