相关疑难解决方法(0)

在Python中,如何检查字符串是否只包含某些字符?

在Python中,如何检查字符串是否只包含某些字符?

我需要检查一个只包含a..z,0..9和的字符串.(期间),没有其他性格.

我可以迭代每个字符并检查字符是a ..z或0..9,或.但那会很慢.

我现在还不清楚如何使用正则表达式来完成它.

它是否正确?你能建议一个更简单的正则表达式或更有效的方法吗?

#Valid chars . a-z 0-9 
def check(test_str):
    import re
    #http://docs.python.org/library/re.html
    #re.search returns None if no position in the string matches the pattern
    #pattern to search for any character other then . a-z 0-9
    pattern = r'[^\.a-z0-9]'
    if re.search(pattern, test_str):
        #Character other then . a-z 0-9 was found
        print 'Invalid : %r' % (test_str,)
    else:
        #No character other then . a-z 0-9 was found
        print 'Valid   : %r' % (test_str,)

check(test_str='abcde.1')
check(test_str='abcde.1#')
check(test_str='ABCDE.12')
check(test_str='_-/>"!@#12345abcde<')

''' …
Run Code Online (Sandbox Code Playgroud)

python regex search character

47
推荐指数
5
解决办法
11万
查看次数

Python模块函数以意想不到的方式使用

基于"在Python中用空格分割字符串",它使用shlex.split智能地分割带引号的字符串,我将有兴趣听到非显而易见的标准库函数解决的其他常见任务.

如果这变成了本周的模块,那也没关系.

python

4
推荐指数
2
解决办法
861
查看次数

标签 统计

python ×2

character ×1

regex ×1

search ×1