python判断字符串中是否只包含英文或者标点
时间: 2023-10-23 14:12:46 浏览: 39
可以使用Python的内置模块`string`和`re`来实现判断字符串中是否只包含英文或者标点。
方法一:使用`string`模块
```python
import string
def is_english_or_punctuation(text):
for char in text:
if char not in string.printable:
return False
if char not in string.ascii_letters and char not in string.punctuation and char != ' ':
return False
return True
text = "This is an example text."
result = is_english_or_punctuation(text)
print(result) # True
text = "这是一个例子,包含中文。"
result = is_english_or_punctuation(text)
print(result) # False
```
方法二:使用正则表达式
```python
import re
def is_english_or_punctuation(text):
pattern = r'^[\w\s' + re.escape(string.punctuation) + ']+$'
return bool(re.match(pattern, text))
text = "This is an example text."
result = is_english_or_punctuation(text)
print(result) # True
text = "这是一个例子,包含中文。"
result = is_english_or_punctuation(text)
print(result) # False
```
以上两种方法都可以实现判断字符串中是否只包含英文或者标点,具体使用哪种方法可以根据实际情况选择。