python判断字符串里的字符_在Python中,如何检查字符串是否只包含某些字符?

1586010002-jmsa.png

In Python, how to check if a string only contains certain characters?

I need to check a string containing only a..z, 0..9, and . (period) and no other character.

I could iterate over each character and check the character is a..z or 0..9, or . but that would be slow.

I am not clear now how to do it with a regular expression.

Is this correct? Can you suggest a simpler regular expression or a more efficient approach.

#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<')

'''

Output:

>>>

Valid : "abcde.1"

Invalid : "abcde.1#"

Invalid : "ABCDE.12"

Invalid : "_-/>"!@#12345abcde<"

'''

解决方案

Final(?) edit

Answer, wrapped up in a function, with annotated interactive session:

>>> import re

>>> def special_match(strg, search=re.compile(r'[^a-z0-9.]').search):

... return not bool(search(strg))

...

>>> special_match("")

True

>>> special_match("az09.")

True

>>> special_match("az09.\n")

False

# The above test case is to catch out any attempt to use re.match()

# with a `$` instead of `\Z` -- see point (6) below.

>>> special_match("az09.#")

False

>>> special_match("az09.X")

False

>>>

Note: There is a comparison with using re.match() further down in this answer. Further timings show that match() would win with much longer strings; match() seems to have a much larger overhead than search() when the final answer is True; this is puzzling (perhaps it's the cost of returning a MatchObject instead of None) and may warrant further rummaging.

==== Earlier text ====

The [previously] accepted answer could use a few improvements:

(1) Presentation gives the appearance of being the result of an interactive Python session:

reg=re.compile('^[a-z0-9\.]+$')

>>>reg.match('jsdlfjdsf12324..3432jsdflsdf')

True

but match() doesn't return True

(2) For use with match(), the ^ at the start of the pattern is redundant, and appears to be slightly slower than the same pattern without the ^

(3) Should foster the use of raw string automatically unthinkingly for any re pattern

(4) The backslash in front of the dot/period is redundant

(5) Slower than the OP's code!

prompt>rem OP's version -- NOTE: OP used raw string!

prompt>\python26\python -mtimeit -s"t='jsdlfjdsf12324..3432jsdflsdf';import

re;reg=re.compile(r'[^a-z0-9\.]')" "not bool(reg.search(t))"

1000000 loops, best of 3: 1.43 usec per loop

prompt>rem OP's version w/o backslash

prompt>\python26\python -mtimeit -s"t='jsdlfjdsf12324..3432jsdflsdf';import

re;reg=re.compile(r'[^a-z0-9.]')" "not bool(reg.search(t))"

1000000 loops, best of 3: 1.44 usec per loop

prompt>rem cleaned-up version of accepted answer

prompt>\python26\python -mtimeit -s"t='jsdlfjdsf12324..3432jsdflsdf';import

re;reg=re.compile(r'[a-z0-9.]+\Z')" "bool(reg.match(t))"

100000 loops, best of 3: 2.07 usec per loop

prompt>rem accepted answer

prompt>\python26\python -mtimeit -s"t='jsdlfjdsf12324..3432jsdflsdf';import

re;reg=re.compile('^[a-z0-9\.]+$')" "bool(reg.match(t))"

100000 loops, best of 3: 2.08 usec per loop

(6) Can produce the wrong answer!!

>>> import re

>>> bool(re.compile('^[a-z0-9\.]+$').match('1234\n'))

True # uh-oh

>>> bool(re.compile('^[a-z0-9\.]+\Z').match('1234\n'))

False

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 可以使用Python的in关键字来判断字符串是否包含指定的子串。示例代码如下: ```python string = "hello world" if "world" in string: print("字符串包含'world'") else: print("字符串包含'world'") ``` 输出结果为:字符串包含'world'。 如果需要判断字符串是否包含多个子串,可以使用多个in关键字进行判断。示例代码如下: ```python string = "hello world" if "hello" in string and "world" in string: print("字符串同时包含'hello'和'world'") else: print("字符串不同时包含'hello'和'world'") ``` 输出结果为:字符串同时包含'hello'和'world'。 ### 回答2: 要在Python判断一个字符串是否包含另一个字符串,可以使用in关键字。该关键字可以用来判断一个字符串是否是另一个字符串的子串。 例如,我们有一个字符串name = "Hello World!",想要判断是否包含子串"World",可以使用以下代码: if "World" in name: print("字符串包含子串'World'") 运行结果为"字符串包含子串'World'",说明name字符串包含子串"World"。 另外,可以结合条件判断语句和循环语句,来判断一个字符串是否包含多个子串。例如: name = "Hello World!" substrings = ["Hello", "World"] for substring in substrings: if substring in name: print(f"字符串包含子串'{substring}'") 运行结果为"字符串包含子串'Hello'"和"字符串包含子串'World'",说明name字符串同时包含子串"Hello"和"World"。 总结:使用in关键字可以判断一个字符串是否包含另一个字符串,可以通过条件判断语句和循环语句来判断多个子串是否包含字符串。 ### 回答3: 要判断一个字符串是否包含特定的字符或者字符串,我们可以使用Python的关键字"in"。通过使用"in"关键字,我们可以直接判断某个字符串是否包含在另一个字符串。 例如,我们想要判断字符串s是否包含字符串sub: ```python s = "hello world" sub = "world" if sub in s: print("字符串s包含字符串sub") else: print("字符串s包含字符串sub") ``` 上述代码,我们首先声明了字符串s和子字符串sub,然后使用"in"关键字判断sub是否在s。如果sub在s,则会输出"字符串s包含字符串sub",否则输出"字符串s包含字符串sub"。 除了"in"关键字外,python字符串还有其他的相关方法可以用于判断字符串是否包含特定字符或子字符串,比如: 1. `find()`方法:返回第一次出现特定子字符串的起始索引,如果找不到则返回-1。 2. `index()`方法:返回第一次出现特定子字符串的起始索引,如果找不到则会抛出ValueError异常。 3. `count()`方法:返回特定子字符串字符串出现的次数。 总之,Python提供了多种方法来判断一个字符串是否包含特定的字符或子字符串,并且可以根据实际需要选择最适合的方法来实现。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值