python 字符串 变量
Sometimes we want to check if the variable or input argument is String and then only perform further actions. We can use isinstance() function to verify that a variable is string or not.
有时我们想检查变量或输入参数是否为String,然后仅执行进一步的操作。 我们可以使用isinstance()函数来验证变量是否为字符串。
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 str
print(isinstance(i, str))
s = 'abc' # string
print(isinstance(s, str))
Output:
输出:
False
True
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 abc
Processing 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 abc
Input Must be String
We can use isinstance() function to check the type of any variable or function arguments.
我们可以使用isinstance()函数来检查任何变量或函数参数的类型。
Reference: isinstance() api doc
翻译自: https://www.journaldev.com/23507/python-check-variable-is-string
python 字符串 变量