python 判断是否为字符串
时间: 2023-04-03 11:02:59 浏览: 63
可以使用 isinstance() 函数来判断一个变量是否为字符串类型,示例代码如下:
```
str = "hello world"
if isinstance(str, str):
print("str 是字符串类型")
else:
print("str 不是字符串类型")
```
输出结果为:
```
str 是字符串类型
```
相关问题
python 判断输出是否为字符串
要判断输出是否为字符串,可以使用isinstance()函数来判断。isinstance()函数可以判断一个对象是否为指定的类型,如果是则返回True,否则返回False。下面是一个示例代码:
```python
output = "Hello, world!"
if isinstance(output, str):
print("Output is a string.")
else:
print("Output is not a string.")
```
在这个示例中,我们首先定义了一个字符串变量output,然后使用isinstance()函数来判断它是否为字符串类型。由于output是一个字符串,所以isinstance()函数返回True,程序输出"Output is a string."。
Python 判断是否包含字符串
在 Python 中,可以使用 `in` 运算符来判断一个字符串是否包含另一个字符串。
例如:
```python
s1 = "Hello, World!"
s2 = "Hello"
if s2 in s1:
print("s1 包含 s2")
else:
print("s1 不包含 s2")
```
输出结果为:
```
s1 包含 s2
```
你也可以使用 `str.find()` 函数来判断字符串是否包含另一个字符串:
```python
s1 = "Hello, World!"
s2 = "Hello"
if s1.find(s2) != -1:
print("s1 包含 s2")
else:
print("s1 不包含 s2")
```
输出结果也是:
```
s1 包含 s2
```