博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python 字符串 变量_Python检查变量是字符串
阅读量:2531 次
发布时间:2019-05-11

本文共 1950 字,大约阅读时间需要 6 分钟。

python 字符串 变量

Sometimes we want to check if the variable or input argument is String and then only perform further actions. We can use to verify that a variable is string or not.

有时我们想检查变量或输入参数是否为String,然后仅执行进一步的操作。 我们可以使用来验证变量是否为字符串。

Python变量是字符串 (Python Variable is String)

Let’s look at a simple example to check if a variable is a string or not.

让我们看一个简单的示例,检查变量是否为字符串。

i = 5  # not strprint(isinstance(i, str))s = 'abc'  # stringprint(isinstance(s, str))

Output:

输出:

FalseTrue

Python函数输入为字符串 (Python Function Input is String)

If you look at above example, we are creating the variable so we already know its type. However, if we have to define a function to process input string then it’s a good idea to check if the input supplied is a string or not.

如果您看上面的示例,我们正在创建变量,因此我们已经知道它的类型。 但是,如果我们必须定义一个函数来处理输入字符串,那么最好检查提供的输入是否为字符串。

Let’s say we have a function defined as:

假设我们有一个定义为的函数:

def process_string(input_str):    print('Processing', input_str)

If we have following code snippet to execute this function:

如果我们有以下代码片段执行此功能:

process_string('abc')process_string(100)

The output will be:

输出将是:

Processing abcProcessing 100

Since we don’t have validation in place for the input argument, our function is processing non-string arguments too.

由于我们没有针对输入参数的验证,因此我们的函数也正在处理非字符串参数。

If we want our function to run its logic for string argument only, then we can add a validation check using isinstance() function.

如果我们希望函数仅对字符串参数运行其逻辑,则可以使用isinstance()函数添加验证检查。

def process_string(input_str):    if (isinstance(input_str, str)):        print('Processing', input_str)    else:        print('Input Must be String')

Now when we call this function as:

现在,当我们将此函数称为:

process_string('abc')process_string(100)

The output will be:

输出将是:

Processing abcInput Must be String

We can use isinstance() function to check the type of any variable or function arguments.

我们可以使用isinstance()函数来检查任何变量或函数参数的类型。

. 检出完整的python脚本和更多Python示例。

Reference:

参考:

翻译自:

python 字符串 变量

转载地址:http://pamzd.baihongyu.com/

你可能感兴趣的文章
jquery扩展 $.fn
查看>>
Markdown指南
查看>>
influxDB的安装和简单使用
查看>>
JPA框架学习
查看>>
JPA、JTA、XA相关索引
查看>>
机器分配
查看>>
php opcode缓存
查看>>
springcloud之Feign、ribbon设置超时时间和重试机制的总结
查看>>
观看杨老师(杨旭)Asp.Net Core MVC入门教程记录
查看>>
UIDynamic(物理仿真)
查看>>
Windows下安装Redis
查看>>
winform非常实用的程序退出方法!!!!!(转自博客园)
查看>>
centos安装vim
查看>>
linux工作调度(计划任务)
查看>>
NIO:与 Buffer 一起使用 Channel
查看>>
Android帧缓冲区(Frame Buffer)硬件抽象层(HAL)模块Gralloc的实现原理分析
查看>>
MFC接收ShellExecute多个参数
查看>>
volatile和synchronized的区别
查看>>
RocketMQ介绍与云服务器安装
查看>>
并发量计算研究
查看>>