标签归档:variables

如何将变量放在字符串中?

问题:如何将变量放在字符串中?

我想int放入一个string。这是我目前正在做的事情:

num = 40
plot.savefig('hanning40.pdf') #problem line

我必须为几个不同的数字运行程序,所以我想做一个循环。但是像这样插入变量不起作用:

plot.savefig('hanning', num, '.pdf')

如何在Python字符串中插入变量?

I would like to put an int into a string. This is what I am doing at the moment:

num = 40
plot.savefig('hanning40.pdf') #problem line

I have to run the program for several different numbers, so I’d like to do a loop. But inserting the variable like this doesn’t work:

plot.savefig('hanning', num, '.pdf')

How do I insert a variable into a Python string?


回答 0

plot.savefig('hanning(%d).pdf' % num)

%运营商,下面的字符串时,允许你插入值到通过格式代码的字符串(%d在这种情况下)。有关更多详细信息,请参见Python文档:

https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting

plot.savefig('hanning(%d).pdf' % num)

The % operator, when following a string, allows you to insert values into that string via format codes (the %d in this case). For more details, see the Python documentation:

https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting


回答 1

哦,很多很多方式…

字符串串联:

plot.savefig('hanning' + str(num) + '.pdf')

转换说明符:

plot.savefig('hanning%s.pdf' % num)

使用局部变量名:

plot.savefig('hanning%(num)s.pdf' % locals()) # Neat trick

使用str.format()

plot.savefig('hanning{0}.pdf'.format(num)) # Note: This is the new preferred way

使用f字符串:

plot.savefig(f'hanning{num}.pdf') # added in Python 3.6

使用string.Template

plot.savefig(string.Template('hanning${num}.pdf').substitute(locals()))

Oh, the many, many ways…

String concatenation:

plot.savefig('hanning' + str(num) + '.pdf')

Conversion Specifier:

plot.savefig('hanning%s.pdf' % num)

Using local variable names:

plot.savefig('hanning%(num)s.pdf' % locals()) # Neat trick

Using str.format():

plot.savefig('hanning{0}.pdf'.format(num)) # Note: This is the new preferred way

Using f-strings:

plot.savefig(f'hanning{num}.pdf') # added in Python 3.6

Using string.Template:

plot.savefig(string.Template('hanning${num}.pdf').substitute(locals()))

回答 2

通过在Python 3.6中引入格式化的字符串文字(简称为“ f-strings”),现在可以使用更简短的语法编写该文字了:

>>> name = "Fred"
>>> f"He said his name is {name}."
'He said his name is Fred.'

通过问题中给出的示例,它看起来像这样

plot.savefig(f'hanning{num}.pdf')

With the introduction of formatted string literals (“f-strings” for short) in Python 3.6, it is now possible to write this with a briefer syntax:

>>> name = "Fred"
>>> f"He said his name is {name}."
'He said his name is Fred.'

With the example given in the question, it would look like this

plot.savefig(f'hanning{num}.pdf')

回答 3

不确定您发布的所有代码到底做什么,但是要回答标题中提出的问题,您可以将+用作常规字符串concat函数以及str()。

"hello " + str(10) + " world" = "hello 10 world"

希望有帮助!

Not sure exactly what all the code you posted does, but to answer the question posed in the title, you can use + as the normal string concat function as well as str().

"hello " + str(10) + " world" = "hello 10 world"

Hope that helps!


回答 4

通常,您可以使用以下命令创建字符串:

stringExample = "someString " + str(someNumber)
print(stringExample)
plot.savefig(stringExample)

In general, you can create strings using:

stringExample = "someString " + str(someNumber)
print(stringExample)
plot.savefig(stringExample)

回答 5

如果您想将多个值放入字符串中,则可以使用 format

nums = [1,2,3]
plot.savefig('hanning{0}{1}{2}.pdf'.format(*nums))

将导致字符串hanning123.pdf。可以使用任何数组来完成。

If you would want to put multiple values into the string you could make use of format

nums = [1,2,3]
plot.savefig('hanning{0}{1}{2}.pdf'.format(*nums))

Would result in the string hanning123.pdf. This can be done with any array.


回答 6

我需要一个扩展版本:我不需要在字符串中嵌入单个数字,而是需要生成一系列格式为’file1.pdf’,’file2.pdf’等的文件名。这就是它的方式工作:

['file' + str(i) + '.pdf' for i in range(1,4)]

I had a need for an extended version of this: instead of embedding a single number in a string, I needed to generate a series of file names of the form ‘file1.pdf’, ‘file2.pdf’ etc. This is how it worked:

['file' + str(i) + '.pdf' for i in range(1,4)]

回答 7

您只需要使用以下命令将num变量转换为字符串

str(num)

You just have to cast the num varriable into a string using

str(num)

如何在正则表达式中使用变量?

问题:如何在正则表达式中使用变量?

我想在a variable内部使用regex,该怎么办Python

TEXTO = sys.argv[1]

if re.search(r"\b(?=\w)TEXTO\b(?!\w)", subject, re.IGNORECASE):
    # Successful match
else:
    # Match attempt failed

I’d like to use a variable inside a regex, how can I do this in Python?

TEXTO = sys.argv[1]

if re.search(r"\b(?=\w)TEXTO\b(?!\w)", subject, re.IGNORECASE):
    # Successful match
else:
    # Match attempt failed

回答 0

从python 3.6开始,您还可以使用文字字符串插值(“ f-strings”)。在您的特定情况下,解决方案是:

if re.search(rf"\b(?=\w){TEXTO}\b(?!\w)", subject, re.IGNORECASE):
    ...do something

编辑:

既然评论中存在一些有关如何处理特殊字符的问题,我想扩展一下我的答案:

原始字符串(’r’):

在正则表达式中处理特殊字符时,您必须了解的主要概念之一是区分字符串文字和正则表达式本身。这是很好的解释在这里

简而言之:

假设您要匹配字符串\b之后,而不是查找单词边界。你必须写:TEXTO\boundary

TEXTO = "Var"
subject = r"Var\boundary"

if re.search(rf"\b(?=\w){TEXTO}\\boundary(?!\w)", subject, re.IGNORECASE):
    print("match")

这仅起作用,因为我们使用的是原始字符串(正则表达式以’r’开头),否则我们必须在正则表达式中写入“ \\\\ boundary”(四个反斜杠)。另外,如果没有’\ r’,\ b’将不再转换为单词边界,而是转换为退格键!

重新转义

基本上在任何特殊字符的前面放置一个空格。因此,如果您希望TEXTO中有特殊字符,则需要编写:

if re.search(rf"\b(?=\w){re.escape(TEXTO)}\b(?!\w)", subject, re.IGNORECASE):
    print("match")

注:对于任何版本> = 3.7蟒:!"%',/:;<=>@,和`都没有逃脱。仅对正则表达式中具有含义的特殊字符进行转义。_因为Python 3.3没有逃脱。(送。这里

大括号:

如果要在使用f字符串的正则表达式中使用量词,则必须使用双花括号。假设您要匹配TEXTO,然后再精确匹配2位数字:

if re.search(rf"\b(?=\w){re.escape(TEXTO)}\d{{2}}\b(?!\w)", subject, re.IGNORECASE):
    print("match")

From python 3.6 on you can also use Literal String Interpolation, “f-strings”. In your particular case the solution would be:

if re.search(rf"\b(?=\w){TEXTO}\b(?!\w)", subject, re.IGNORECASE):
    ...do something

EDIT:

Since there have been some questions in the comment on how to deal with special characters I’d like to extend my answer:

raw strings (‘r’):

One of the main concepts you have to understand when dealing with special characters in regular expressions is to distinguish between string literals and the regular expression itself. It is very well explained here:

In short:

Let’s say instead of finding a word boundary \b after TEXTO you want to match the string \boundary. The you have to write:

TEXTO = "Var"
subject = r"Var\boundary"

if re.search(rf"\b(?=\w){TEXTO}\\boundary(?!\w)", subject, re.IGNORECASE):
    print("match")

This only works because we are using a raw-string (the regex is preceded by ‘r’), otherwise we must write “\\\\boundary” in the regex (four backslashes). Additionally, without ‘\r’, \b’ would not converted to a word boundary anymore but to a backspace!

re.escape:

Basically puts a backspace in front of any special character. Hence, if you expect a special character in TEXTO, you need to write:

if re.search(rf"\b(?=\w){re.escape(TEXTO)}\b(?!\w)", subject, re.IGNORECASE):
    print("match")

NOTE: For any version >= python 3.7: !, ", %, ', ,, /, :, ;, <, =, >, @, and ` are not escaped. Only special characters with meaning in a regex are still escaped. _ is not escaped since Python 3.3.(s. here)

Curly braces:

If you want to use quantifiers within the regular expression using f-strings, you have to use double curly braces. Let’s say you want to match TEXTO followed by exactly 2 digits:

if re.search(rf"\b(?=\w){re.escape(TEXTO)}\d{{2}}\b(?!\w)", subject, re.IGNORECASE):
    print("match")

回答 1

您必须将正则表达式构建为字符串:

TEXTO = sys.argv[1]
my_regex = r"\b(?=\w)" + re.escape(TEXTO) + r"\b(?!\w)"

if re.search(my_regex, subject, re.IGNORECASE):
    etc.

请注意使用,re.escape这样如果您的文本中包含特殊字符,则不会这样解释它们。

You have to build the regex as a string:

TEXTO = sys.argv[1]
my_regex = r"\b(?=\w)" + re.escape(TEXTO) + r"\b(?!\w)"

if re.search(my_regex, subject, re.IGNORECASE):
    etc.

Note the use of re.escape so that if your text has special characters, they won’t be interpreted as such.


回答 2

if re.search(r"\b(?<=\w)%s\b(?!\w)" % TEXTO, subject, re.IGNORECASE):

这会将TEXTO中的内容作为字符串插入到正则表达式中。

if re.search(r"\b(?<=\w)%s\b(?!\w)" % TEXTO, subject, re.IGNORECASE):

This will insert what is in TEXTO into the regex as a string.


回答 3

rx = r'\b(?<=\w){0}\b(?!\w)'.format(TEXTO)
rx = r'\b(?<=\w){0}\b(?!\w)'.format(TEXTO)

回答 4

我发现通过将多个较小的模式串在一起来构建正则表达式模式非常方便。

import re

string = "begin:id1:tag:middl:id2:tag:id3:end"
re_str1 = r'(?<=(\S{5})):'
re_str2 = r'(id\d+):(?=tag:)'
re_pattern = re.compile(re_str1 + re_str2)
match = re_pattern.findall(string)
print(match)

输出:

[('begin', 'id1'), ('middl', 'id2')]

I find it very convenient to build a regular expression pattern by stringing together multiple smaller patterns.

import re

string = "begin:id1:tag:middl:id2:tag:id3:end"
re_str1 = r'(?<=(\S{5})):'
re_str2 = r'(id\d+):(?=tag:)'
re_pattern = re.compile(re_str1 + re_str2)
match = re_pattern.findall(string)
print(match)

Output:

[('begin', 'id1'), ('middl', 'id2')]

回答 5

我同意以上所有条件,除非:

sys.argv[1] 就像 Chicken\d{2}-\d{2}An\s*important\s*anchor

sys.argv[1] = "Chicken\d{2}-\d{2}An\s*important\s*anchor"

您不想使用re.escape,因为在这种情况下,您希望它的行为类似于正则表达式

TEXTO = sys.argv[1]

if re.search(r"\b(?<=\w)" + TEXTO + "\b(?!\w)", subject, re.IGNORECASE):
    # Successful match
else:
    # Match attempt failed

I agree with all the above unless:

sys.argv[1] was something like Chicken\d{2}-\d{2}An\s*important\s*anchor

sys.argv[1] = "Chicken\d{2}-\d{2}An\s*important\s*anchor"

you would not want to use re.escape, because in that case you would like it to behave like a regex

TEXTO = sys.argv[1]

if re.search(r"\b(?<=\w)" + TEXTO + "\b(?!\w)", subject, re.IGNORECASE):
    # Successful match
else:
    # Match attempt failed

回答 6

我需要搜索彼此相似的用户名,Ned Batchelder所说的话非常有用。但是,当我使用re.compile创建我的搜索项时,发现输出更清晰:

pattern = re.compile(r"("+username+".*):(.*?):(.*?):(.*?):(.*)"
matches = re.findall(pattern, lines)

可以使用以下命令打印输出:

print(matches[1]) # prints one whole matching line (in this case, the first line)
print(matches[1][3]) # prints the fourth character group (established with the parentheses in the regex statement) of the first line.

I needed to search for usernames that are similar to each other, and what Ned Batchelder said was incredibly helpful. However, I found I had cleaner output when I used re.compile to create my re search term:

pattern = re.compile(r"("+username+".*):(.*?):(.*?):(.*?):(.*)"
matches = re.findall(pattern, lines)

Output can be printed using the following:

print(matches[1]) # prints one whole matching line (in this case, the first line)
print(matches[1][3]) # prints the fourth character group (established with the parentheses in the regex statement) of the first line.

回答 7

您可以使用formatgrammer suger 尝试另一种用法:

re_genre = r'{}'.format(your_variable)
regex_pattern = re.compile(re_genre)  

you can try another usage using format grammer suger:

re_genre = r'{}'.format(your_variable)
regex_pattern = re.compile(re_genre)  

回答 8

您也可以为此使用format关键字。Format方法将{}占位符替换为您作为参数传递给format方法的变量。

if re.search(r"\b(?=\w)**{}**\b(?!\w)".**format(TEXTO)**, subject, re.IGNORECASE):
    # Successful match**strong text**
else:
    # Match attempt failed

You can use format keyword as well for this.Format method will replace {} placeholder to the variable which you passed to the format method as an argument.

if re.search(r"\b(?=\w)**{}**\b(?!\w)".**format(TEXTO)**, subject, re.IGNORECASE):
    # Successful match**strong text**
else:
    # Match attempt failed

回答 9

更多例子

我有带有流文件的configus.yml

"pattern":
  - _(\d{14})_
"datetime_string":
  - "%m%d%Y%H%M%f"

在我使用的python代码中

data_time_real_file=re.findall(r""+flows[flow]["pattern"][0]+"", latest_file)

more example

I have configus.yml with flows files

"pattern":
  - _(\d{14})_
"datetime_string":
  - "%m%d%Y%H%M%f"

in python code I use

data_time_real_file=re.findall(r""+flows[flow]["pattern"][0]+"", latest_file)

python:如何识别变量是数组还是标量

问题:python:如何识别变量是数组还是标量

我有一个接受参数的函数NBins。我想用标量50或数组对此函数进行调用[0, 10, 20, 30]。我如何识别函数的长度NBins是多少?或换句话说,如果它是标量或向量?

我尝试了这个:

>>> N=[2,3,5]
>>> P = 5
>>> len(N)
3
>>> len(P)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: object of type 'int' has no len()
>>> 

正如你看到的,我不能申请lenP,因为它不是一个数组….有什么样isarrayisscalar在Python?

谢谢

I have a function that takes the argument NBins. I want to make a call to this function with a scalar 50 or an array [0, 10, 20, 30]. How can I identify within the function, what the length of NBins is? or said differently, if it is a scalar or a vector?

I tried this:

>>> N=[2,3,5]
>>> P = 5
>>> len(N)
3
>>> len(P)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: object of type 'int' has no len()
>>> 

As you see, I can’t apply len to P, since it’s not an array…. Is there something like isarray or isscalar in python?

thanks


回答 0

>>> isinstance([0, 10, 20, 30], list)
True
>>> isinstance(50, list)
False

要支持任何类型的序列,请选中collections.Sequence而不是list

注意isinstance还支持一个元组类,type(x) in (..., ...)应避免检查,这是不必要的。

您可能还想检查 not isinstance(x, (str, unicode))

>>> isinstance([0, 10, 20, 30], list)
True
>>> isinstance(50, list)
False

To support any type of sequence, check collections.Sequence instead of list.

note: isinstance also supports a tuple of classes, check type(x) in (..., ...) should be avoided and is unnecessary.

You may also wanna check not isinstance(x, (str, unicode))


回答 1

先前的答案假定该数组是python标准列表。作为经常使用numpy的人,我建议使用以下Python测试:

if hasattr(N, "__len__")

Previous answers assume that the array is a python standard list. As someone who uses numpy often, I’d recommend a very pythonic test of:

if hasattr(N, "__len__")

回答 2

将@jamylak和@ jpaddison3的答案结合在一起,如果您需要对作为输入的numpy数组保持鲁棒性,并以与列表相同的方式处理它们,则应使用

import numpy as np
isinstance(P, (list, tuple, np.ndarray))

对于list,tuple和numpy数组的子类,这是可靠的。

而且,如果您还想对序列的所有其他子类(不仅是列表和元组)具有鲁棒性,请使用

import collections
import numpy as np
isinstance(P, (collections.Sequence, np.ndarray))

为什么要用这种方法isinstance而不是type(P)与目标值进行比较?这是一个示例,我们制作并研究NewListlist的一个琐碎子类的行为。

>>> class NewList(list):
...     isThisAList = '???'
... 
>>> x = NewList([0,1])
>>> y = list([0,1])
>>> print x
[0, 1]
>>> print y
[0, 1]
>>> x==y
True
>>> type(x)
<class '__main__.NewList'>
>>> type(x) is list
False
>>> type(y) is list
True
>>> type(x).__name__
'NewList'
>>> isinstance(x, list)
True

尽管xy比较平等,通过处理它们type会导致不同的行为。然而,由于x是的子类的实例list,使用isinstance(x,list)得到所需的行为和治疗xy以相同的方式。

Combining @jamylak and @jpaddison3’s answers together, if you need to be robust against numpy arrays as the input and handle them in the same way as lists, you should use

import numpy as np
isinstance(P, (list, tuple, np.ndarray))

This is robust against subclasses of list, tuple and numpy arrays.

And if you want to be robust against all other subclasses of sequence as well (not just list and tuple), use

import collections
import numpy as np
isinstance(P, (collections.Sequence, np.ndarray))

Why should you do things this way with isinstance and not compare type(P) with a target value? Here is an example, where we make and study the behaviour of NewList, a trivial subclass of list.

>>> class NewList(list):
...     isThisAList = '???'
... 
>>> x = NewList([0,1])
>>> y = list([0,1])
>>> print x
[0, 1]
>>> print y
[0, 1]
>>> x==y
True
>>> type(x)
<class '__main__.NewList'>
>>> type(x) is list
False
>>> type(y) is list
True
>>> type(x).__name__
'NewList'
>>> isinstance(x, list)
True

Despite x and y comparing as equal, handling them by type would result in different behaviour. However, since x is an instance of a subclass of list, using isinstance(x,list) gives the desired behaviour and treats x and y in the same manner.


回答 3

numpy中有与isscalar()等效的东西吗?是。

>>> np.isscalar(3.1)
True
>>> np.isscalar([3.1])
False
>>> np.isscalar(False)
True

Is there an equivalent to isscalar() in numpy? Yes.

>>> np.isscalar(3.1)
True
>>> np.isscalar([3.1])
False
>>> np.isscalar(False)
True

回答 4

虽然@jamylak的方法更好,但这是另一种方法

>>> N=[2,3,5]
>>> P = 5
>>> type(P) in (tuple, list)
False
>>> type(N) in (tuple, list)
True

While, @jamylak’s approach is the better one, here is an alternative approach

>>> N=[2,3,5]
>>> P = 5
>>> type(P) in (tuple, list)
False
>>> type(N) in (tuple, list)
True

回答 5

另一种替代方法(使用类属性):

N = [2,3,5]
P = 5

type(N).__name__ == 'list'
True

type(P).__name__ == 'int'
True

type(N).__name__ in ('list', 'tuple')
True

无需导入任何东西。

Another alternative approach (use of class name property):

N = [2,3,5]
P = 5

type(N).__name__ == 'list'
True

type(P).__name__ == 'int'
True

type(N).__name__ in ('list', 'tuple')
True

No need to import anything.


回答 6

这是我找到的最佳方法:检查__len__和的存在__getitem__

您可能会问为什么?原因包括:

  1. 该流行方法isinstance(obj, abc.Sequence)在某些对象(包括PyTorch的Tensor)上失败,因为它们未实现__contains__
  2. 不幸的是,Python的collections.abc中没有任何东西可以检查__len__并且__getitem__我认为这是处理类似数组对象的最小方法。
  3. 它适用于列表,元组,ndarray,Tensor等。

因此,事不宜迟:

def is_array_like(obj, string_is_array=False, tuple_is_array=True):
    result = hasattr(obj, "__len__") and hasattr(obj, '__getitem__') 
    if result and not string_is_array and isinstance(obj, (str, abc.ByteString)):
        result = False
    if result and not tuple_is_array and isinstance(obj, tuple):
        result = False
    return result

请注意,我添加了默认参数,因为大多数时候您可能希望将字符串视为值,而不是数组。元组也是如此。

Here is the best approach I have found: Check existence of __len__ and __getitem__.

You may ask why? The reasons includes:

  1. The popular method isinstance(obj, abc.Sequence) fails on some objects including PyTorch’s Tensor because they do not implement __contains__.
  2. Unfortunately, there is nothing in Python’s collections.abc that checks for only __len__ and __getitem__ which I feel are minimal methods for array-like objects.
  3. It works on list, tuple, ndarray, Tensor etc.

So without further ado:

def is_array_like(obj, string_is_array=False, tuple_is_array=True):
    result = hasattr(obj, "__len__") and hasattr(obj, '__getitem__') 
    if result and not string_is_array and isinstance(obj, (str, abc.ByteString)):
        result = False
    if result and not tuple_is_array and isinstance(obj, tuple):
        result = False
    return result

Note that I’ve added default parameters because most of the time you might want to consider strings as values, not arrays. Similarly for tuples.


回答 7

>>> N=[2,3,5]
>>> P = 5
>>> type(P)==type(0)
True
>>> type([1,2])==type(N)
True
>>> type(P)==type([1,2])
False
>>> N=[2,3,5]
>>> P = 5
>>> type(P)==type(0)
True
>>> type([1,2])==type(N)
True
>>> type(P)==type([1,2])
False

回答 8

您可以检查变量的数据类型。

N = [2,3,5]
P = 5
type(P)

它将以P的数据类型输出。

<type 'int'>

这样就可以区分它是整数还是数组。

You can check data type of variable.

N = [2,3,5]
P = 5
type(P)

It will give you out put as data type of P.

<type 'int'>

So that you can differentiate that it is an integer or an array.


回答 9

令我惊讶的是,这样的基本问题似乎在python中没有即时的答案。在我看来,几乎所有建议的答案都使用某种类型检查,通常在python中不建议这样做,并且它们似乎仅限于特定情况(它们因使用不同的数字类型或非元组或列表的通用可迭代对象而失败)。

对我来说,更好的方法是导入numpy并使用array.size,例如:

>>> a=1
>>> np.array(a)
Out[1]: array(1)

>>> np.array(a).size
Out[2]: 1

>>> np.array([1,2]).size
Out[3]: 2

>>> np.array('125')
Out[4]: 1

另请注意:

>>> len(np.array([1,2]))

Out[5]: 2

但:

>>> len(np.array(a))
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-40-f5055b93f729> in <module>()
----> 1 len(np.array(a))

TypeError: len() of unsized object

I am surprised that such a basic question doesn’t seem to have an immediate answer in python. It seems to me that nearly all proposed answers use some kind of type checking, that is usually not advised in python and they seem restricted to a specific case (they fail with different numerical types or generic iteratable objects that are not tuples or lists).

For me, what works better is importing numpy and using array.size, for example:

>>> a=1
>>> np.array(a)
Out[1]: array(1)

>>> np.array(a).size
Out[2]: 1

>>> np.array([1,2]).size
Out[3]: 2

>>> np.array('125')
Out[4]: 1

Note also:

>>> len(np.array([1,2]))

Out[5]: 2

but:

>>> len(np.array(a))
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-40-f5055b93f729> in <module>()
----> 1 len(np.array(a))

TypeError: len() of unsized object

回答 10

只需使用size代替len

>>> from numpy import size
>>> N = [2, 3, 5]
>>> size(N)
3
>>> N = array([2, 3, 5])
>>> size(N)
3
>>> P = 5
>>> size(P)
1

Simply use size instead of len!

>>> from numpy import size
>>> N = [2, 3, 5]
>>> size(N)
3
>>> N = array([2, 3, 5])
>>> size(N)
3
>>> P = 5
>>> size(P)
1

回答 11

preds_test [0]的形状为(128,128,1),让我们使用isinstance()函数检查其数据类型isinstance接受2个参数。第一个参数是数据第二个参数是数据类型isinstance(preds_test [0],np.ndarray)给出Output为True。这意味着preds_test [0]是一个数组。

preds_test[0] is of shape (128,128,1) Lets check its data type using isinstance() function isinstance takes 2 arguments. 1st argument is data 2nd argument is data type isinstance(preds_test[0], np.ndarray) gives Output as True. It means preds_test[0] is an array.


回答 12

为了回答标题中的问题,判断变量是否为标量的直接方法是尝试将其转换为浮点数。如果得到TypeError,则不是。

N = [1, 2, 3]
try:
    float(N)
except TypeError:
    print('it is not a scalar')
else:
    print('it is a scalar')

To answer the question in the title, a direct way to tell if a variable is a scalar is to try to convert it to a float. If you get TypeError, it’s not.

N = [1, 2, 3]
try:
    float(N)
except TypeError:
    print('it is not a scalar')
else:
    print('it is a scalar')

在Jinja中设置变量

问题:在Jinja中设置变量

我想知道如何在Jinja中使用另一个变量设置变量。我会解释,我有一个子菜单,我想显示哪个链接处于活动状态。我尝试了这个:

{% set active_link = {{recordtype}} -%}

其中recordtype是为我的模板提供的变量。

I would like to know how can I set a variable with another variable in jinja. I will explain, I have got a submenu and I would like show which link is active. I tried this:

{% set active_link = {{recordtype}} -%}

where recordtype is a variable given for my template.


回答 0

{{ }}告诉模板打印值,这在您尝试执行的表达式中将不起作用。而是使用{% set %}template标记,然后以与普通python代码相同的方式分配值。

{% set testing = 'it worked' %}
{% set another = testing %}
{{ another }}

结果:

it worked

{{ }} tells the template to print the value, this won’t work in expressions like you’re trying to do. Instead, use the {% set %} template tag and then assign the value the same way you would in normal python code.

{% set testing = 'it worked' %}
{% set another = testing %}
{{ another }}

Result:

it worked

回答 1

多个变量分配的不错简写

{% set label_cls, field_cls = "col-md-7", "col-md-3" %}

Nice shorthand for Multiple variable assignments

{% set label_cls, field_cls = "col-md-7", "col-md-3" %}

回答 2

像这样设置

{% set active_link = recordtype -%}

Just Set it up like this

{% set active_link = recordtype -%}

在if语句中初始化的变量的作用域是什么?

问题:在if语句中初始化的变量的作用域是什么?

我是Python的新手,所以这可能是一个简单的范围界定问题。Python文件(模块)中的以下代码使我有些困惑:

if __name__ == '__main__':
    x = 1

print x

在我使用过的其他语言中,此代码将引发异常,因为该x变量是if语句的局部变量,不应在其外部存在。但是此代码将执行并打印1。任何人都可以解释此行为吗?是否在模块中创建的所有变量都是全局的/可用于整个模块?

I’m new to Python, so this is probably a simple scoping question. The following code in a Python file (module) is confusing me slightly:

if __name__ == '__main__':
    x = 1

print x

In other languages I’ve worked in, this code would throw an exception, as the x variable is local to the if statement and should not exist outside of it. But this code executes, and prints 1. Can anyone explain this behavior? Are all variables created in a module global/available to the entire module?


回答 0

Python变量的作用域是分配给它们的最里面的函数,类或模块。控制块(如ifwhile块)不计在内,因此在内分配的变量的if作用域仍限于函数,类或模块。

(由生成器表达式或list / set / dict理解定义的隐式函数与lambda表达式一样进行计数。您不能将赋值语句填充到其中任何一个中,但是lambda参数和for子句目标是隐式赋值。)

Python variables are scoped to the innermost function, class, or module in which they’re assigned. Control blocks like if and while blocks don’t count, so a variable assigned inside an if is still scoped to a function, class, or module.

(Implicit functions defined by a generator expression or list/set/dict comprehension do count, as do lambda expressions. You can’t stuff an assignment statement into any of those, but lambda parameters and for clause targets are implicit assignment.)


回答 1

是的,它们在同一个“本地范围”中,实际上这样的代码在Python中很常见:

if condition:
  x = 'something'
else:
  x = 'something else'

use(x)

请注意,x不会在条件之前声明或初始化它,例如在C或Java中。

换句话说,Python没有块级作用域。不过,请注意以下示例

if False:
    x = 3
print(x)

这显然会引发NameErrorexceptions。

Yes, they’re in the same “local scope”, and actually code like this is common in Python:

if condition:
  x = 'something'
else:
  x = 'something else'

use(x)

Note that x isn’t declared or initialized before the condition, like it would be in C or Java, for example.

In other words, Python does not have block-level scopes. Be careful, though, with examples such as

if False:
    x = 3
print(x)

which would clearly raise a NameError exception.


回答 2

python中的作用域遵循以下顺序:

  • 搜索本地范围

  • 搜索所有封闭函数的范围

  • 搜索全球范围

  • 搜索内置

来源

请注意,if未列出其他循环/分支构造-仅类,函数和模块在Python中提供了作用域,因此,在if块中声明的任何内容都与在该块之外清除的任何内容具有相同的作用域。在编译时不检查变量,这就是为什么其他语言会引发异常的原因。在python中,只要变量在您需要时存在,就不会抛出异常。

Scope in python follows this order:

  • Search the local scope

  • Search the scope of any enclosing functions

  • Search the global scope

  • Search the built-ins

(source)

Notice that if and other looping/branching constructs are not listed – only classes, functions, and modules provide scope in Python, so anything declared in an if block has the same scope as anything decleared outside the block. Variables aren’t checked at compile time, which is why other languages throw an exception. In python, so long as the variable exists at the time you require it, no exception will be thrown.


回答 3

正如Eli所说,Python不需要变量声明。在C中,您会说:

int x;
if(something)
    x = 1;
else
    x = 2;

但在Python中声明是隐式的,因此当您分配给x时,它会自动声明。这是因为Python是动态类型的-它无法在静态类型的语言中工作,因为取决于所使用的路径,可能会在未声明的情况下使用变量。这将在编译时以静态类型的语言捕获,但是允许使用动态类型的语言。

if由于此问题,静态类型的语言仅限于必须在语句之外声明变量的唯一原因。拥抱动态!

As Eli said, Python doesn’t require variable declaration. In C you would say:

int x;
if(something)
    x = 1;
else
    x = 2;

but in Python declaration is implicit, so when you assign to x it is automatically declared. It’s because Python is dynamically typed – it wouldn’t work in a statically typed language, because depending on the path used, a variable might be used without being declared. This would be caught at compile time in a statically typed language, but with a dynamically typed language it’s allowed.

The only reason that a statically typed language is limited to having to declare variables outside of if statements in because of this problem. Embrace the dynamic!


回答 4

与C之类的语言不同,Python变量在它所出现的整个函数(或类,模块)的范围内,而不仅仅是在最内部的“块”中。就像您int x在函数(或类,模块)的顶部声明的一样,只是在Python中不必声明变量。

请注意,x仅在运行时(即,进入print x语句时)检查变量的存在。如果__name__不相等"__main__",则会出现异常:NameError: name 'x' is not defined

Unlike languages such as C, a Python variable is in scope for the whole of the function (or class, or module) where it appears, not just in the innermost “block”. It is as though you declared int x at the top of the function (or class, or module), except that in Python you don’t have to declare variables.

Note that the existence of the variable x is checked only at runtime — that is, when you get to the print x statement. If __name__ didn’t equal "__main__" then you would get an exception: NameError: name 'x' is not defined.


回答 5

是。for范围也是如此。但是当然不起作用。

在您的示例中:如果if语句中的条件为false,x则不会定义。

Yes. It is also true for for scope. But not functions of course.

In your example: if the condition in the if statement is false, x will not be defined though.


回答 6

您是从命令行执行此代码的,因此if条件为true且x已设置。比较:

>>> if False:
    y = 42


>>> y
Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    y
NameError: name 'y' is not defined

you’re executing this code from command line therefore if conditions is true and x is set. Compare:

>>> if False:
    y = 42


>>> y
Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    y
NameError: name 'y' is not defined

回答 7

请注意,由于仅在运行时检查Python类型,因此您可以使用如下代码:

if True:
    x = 2
    y = 4
else:
    x = "One"
    y = "Two"
print(x + y)

但是我很难考虑由于类型问题而导致代码无错误运行的其他方式。

And note that since Python types are only checked at runtime you can have code like:

if True:
    x = 2
    y = 4
else:
    x = "One"
    y = "Two"
print(x + y)

But I’m having trouble thinking of other ways in which the code would operate without an error because of type issues.


Python中单个下划线“ _”变量的用途是什么?

问题:Python中单个下划线“ _”变量的用途是什么?

此代码中的_after 是什么意思for

if tbh.bag:
   n = 0
   for _ in tbh.bag.atom_set():
      n += 1

What is the meaning of _ after for in this code?

if tbh.bag:
   n = 0
   for _ in tbh.bag.atom_set():
      n += 1

回答 0

_ 在Python中有4种主要的常规用法:

  1. 在交互式解释器会话中保存上次执行的表达式的结果。此先例是由标准CPython解释器设置的,其他解释器也纷纷效仿
  2. 有关在i18n中进行翻译查找的信息,请参见 gettext 例如,文档),如代码所示: raise forms.ValidationError(_("Please enter a correct username"))
  3. 作为通用“一次性”的变量名指示函数结果的一部分被故意忽略(在概念上,它被丢弃。),如类似的代码: label, has_label, _ = text.partition(':')
  4. 作为函数定义的一部分(使用deflambda),其中的签名是固定的(例如,通过回调或父类API),但是此特定函数实现不需要所有参数,如代码所示:callback = lambda _: True

(很长一段时间以来,这个答案只列出了前三个用例,但是第四个用例经常出现,如前所述 这里,将值得明确列出)

后者的“抛弃型变量或参数名称”用例可能与翻译查找用例冲突,因此有必要避免_在也将其用于i18n转换的任何代码块中将其用作抛弃型变量(许多人更喜欢双下划线,__正是由于这个原因而将其作为一次性变量)。

_ has 4 main conventional uses in Python:

  1. To hold the result of the last executed expression(/statement) in an interactive interpreter session. This precedent was set by the standard CPython interpreter, and other interpreters have followed suit
  2. For translation lookup in i18n (see the gettext documentation for example), as in code like: raise forms.ValidationError(_("Please enter a correct username"))
  3. As a general purpose “throwaway” variable name to indicate that part of a function result is being deliberately ignored (Conceptually, it is being discarded.), as in code like: label, has_label, _ = text.partition(':').
  4. As part of a function definition (using either def or lambda), where the signature is fixed (e.g. by a callback or parent class API), but this particular function implementation doesn’t need all of the parameters, as in code like: callback = lambda _: True

(For a long time this answer only listed the first three use cases, but the fourth case came up often enough, as noted here, to be worth listing explicitly)

The latter “throwaway variable or parameter name” uses cases can conflict with the translation lookup use case, so it is necessary to avoid using _ as a throwaway variable in any code block that also uses it for i18n translation (many folks prefer a double-underscore, __, as their throwaway variable for exactly this reason).


回答 1

它只是一个变量名,在python中通常_用于丢弃变量。它仅表示循环变量未实际使用。

It’s just a variable name, and it’s conventional in python to use _ for throwaway variables. It just indicates that the loop variable isn’t actually used.


回答 2

下划线在Python中_被视为“ 我不在乎 ”或“ 抛出 ”变量

  • python解释器将最后一个表达式值存储到名为的特殊变量中_

    >>> 10 
    10
    
    >>> _ 
    10
    
    >>> _ * 3 
    30
  • 下划线_也用于忽略特定值。如果不需要特定值或不使用这些值,只需将这些值分配给下划线即可。

    开箱时忽略值

    x, _, y = (1, 2, 3)
    
    >>> x
    1
    
    >>> y 
    3

    忽略索引

    for _ in range(10):     
        do_something()

Underscore _ is considered as “I don’t Care” or “Throwaway” variable in Python

  • The python interpreter stores the last expression value to the special variable called _.

    >>> 10 
    10
    
    >>> _ 
    10
    
    >>> _ * 3 
    30
    
  • The underscore _ is also used for ignoring the specific values. If you don’t need the specific values or the values are not used, just assign the values to underscore.

    Ignore a value when unpacking

    x, _, y = (1, 2, 3)
    
    >>> x
    1
    
    >>> y 
    3
    

    Ignore the index

    for _ in range(10):     
        do_something()
    

回答 3

在Python中使用下划线有5种情况。

  1. 用于将最后一个表达式的值存储在解释器中。

  2. 用于忽略特定值。(所谓的“我不在乎”)

  3. 给变量或函数的名称赋予特殊的含义和功能。

  4. 用作“国际化(i18n)”或“本地化(l10n)”功能。

  5. 分隔数字文字值的数字。

是一篇不错的文章,上面有mingrammer的示例。

There are 5 cases for using the underscore in Python.

  1. For storing the value of last expression in interpreter.

  2. For ignoring the specific values. (so-called “I don’t care”)

  3. To give special meanings and functions to name of vartiables or functions.

  4. To use as ‘Internationalization(i18n)’ or ‘Localization(l10n)’ functions.

  5. To separate the digits of number literal value.

Here is a nice article with examples by mingrammer.


回答 4

就Python语言而言,_没有特殊含义。与或一样,它是有效的标识符_foofoo__f_o_o_

的任何特殊含义_纯属约定。常见几种情况:

  • 如果不打算使用变量,但是语法/语义需要一个虚拟名称。

    # iteration disregarding content
    sum(1 for _ in some_iterable)
    # unpacking disregarding specific elements
    head, *_ = values
    # function disregarding its argument
    def callback(_): return True
  • 许多REPL / shell将最后一个顶级表达式的结果存储到builtins._

    特殊的标识符_在交互式解释器中用于存储上一次评估的结果。它存储在builtins模块中。如果不在交互模式下,_则没有特殊含义并且未定义。[ 来源 ]

    由于查找名称的方式,除非由全局或局部_定义遮盖,否则裸_指的是builtins._

    >>> 42
    42
    >>> f'the last answer is {_}'
    'the last answer is 42'
    >>> _
    'the last answer is 42'
    >>> _ = 4  # shadow ``builtins._`` with global ``_``
    >>> 23
    23
    >>> _
    4

    注意:某些外壳程序(例如)ipython不分配给builtins._而是特例_

  • 在上下文中,国际化和本地化_用作主要翻译功能的别名。

    gettext.gettext(消息)

    根据当前的全局域,语言和语言环境目录,返回消息的本地化翻译。在本地命名空间中,此函数通常别名为_()(请参见下面的示例)。

As far as the Python languages is concerned, _ has no special meaning. It is a valid identifier just like _foo, foo_ or _f_o_o_.

Any special meaning of _ is purely by convention. Several cases are common:

  • A dummy name when a variable is not intended to be used, but a name is required by syntax/semantics.

    # iteration disregarding content
    sum(1 for _ in some_iterable)
    # unpacking disregarding specific elements
    head, *_ = values
    # function disregarding its argument
    def callback(_): return True
    
  • Many REPLs/shells store the result of the last top-level expression to builtins._.

    The special identifier _ is used in the interactive interpreter to store the result of the last evaluation; it is stored in the builtins module. When not in interactive mode, _ has no special meaning and is not defined. [source]

    Due to the way names are looked up, unless shadowed by a global or local _ definition the bare _ refers to builtins._ .

    >>> 42
    42
    >>> f'the last answer is {_}'
    'the last answer is 42'
    >>> _
    'the last answer is 42'
    >>> _ = 4  # shadow ``builtins._`` with global ``_``
    >>> 23
    23
    >>> _
    4
    

    Note: Some shells such as ipython do not assign to builtins._ but special-case _.

  • In the context internationalization and localization, _ is used as an alias for the primary translation function.

    gettext.gettext(message)

    Return the localized translation of message, based on the current global domain, language, and locale directory. This function is usually aliased as _() in the local namespace (see examples below).


如何检查变量是否存在?

问题:如何检查变量是否存在?

我想检查一个变量是否存在。现在我正在做这样的事情:

try:
   myVar
except NameError:
   # Do something.

是否有其他方法无一exceptions?

I want to check if a variable exists. Now I’m doing something like this:

try:
   myVar
except NameError:
   # Do something.

Are there other ways without exceptions?


回答 0

要检查是否存在局部变量:

if 'myVar' in locals():
  # myVar exists.

要检查是否存在全局变量:

if 'myVar' in globals():
  # myVar exists.

要检查对象是否具有属性:

if hasattr(obj, 'attr_name'):
  # obj.attr_name exists.

To check the existence of a local variable:

if 'myVar' in locals():
  # myVar exists.

To check the existence of a global variable:

if 'myVar' in globals():
  # myVar exists.

To check if an object has an attribute:

if hasattr(obj, 'attr_name'):
  # obj.attr_name exists.

回答 1

使用中那些尚未被定义或组(或明或暗地)变量几乎总是一件坏事任何语言,因为这往往预示着该计划的逻辑还没有被恰当地考虑,并有可能的结果行为无法预测。

如果您需要在Python中执行此操作,以下与您的操作类似的技巧将确保变量在使用前具有一定的价值:

try:
    myVar
except NameError:
    myVar = None

# Now you're free to use myVar without Python complaining.

但是,我仍然不认为这是个好主意-在我看来,您应该尝试重构代码,以免发生这种情况。

The use of variables that have yet to been defined or set (implicitly or explicitly) is almost always a bad thing in any language, since it often indicates that the logic of the program hasn’t been thought through properly, and is likely to result in unpredictable behaviour.

If you need to do it in Python, the following trick, which is similar to yours, will ensure that a variable has some value before use:

try:
    myVar
except NameError:
    myVar = None

# Now you're free to use myVar without Python complaining.

However, I’m still not convinced that’s a good idea – in my opinion, you should try to refactor your code so that this situation does not occur.


回答 2

一种简单的方法是一开始就初始化它 myVar = None

然后稍后:

if myVar is not None:
    # Do something

A simple way is to initialize it at first saying myVar = None

Then later on:

if myVar is not None:
    # Do something

回答 3

使用try / except是测试变量是否存在的最佳方法。但是几乎可以肯定,有一种比设置/测试全局变量更好的方法。

例如,如果您想在第一次调用某个函数时初始化模块级变量,那么最好使用如下代码:

my_variable = None

def InitMyVariable():
  global my_variable
  if my_variable is None:
    my_variable = ...

Using try/except is the best way to test for a variable’s existence. But there’s almost certainly a better way of doing whatever it is you’re doing than setting/testing global variables.

For example, if you want to initialize a module-level variable the first time you call some function, you’re better off with code something like this:

my_variable = None

def InitMyVariable():
  global my_variable
  if my_variable is None:
    my_variable = ...

回答 4

对于对象/模块,您还可以

'var' in dir(obj)

例如,

>>> class Something(object):
...     pass
...
>>> c = Something()
>>> c.a = 1
>>> 'a' in dir(c)
True
>>> 'b' in dir(c)
False

for objects/modules, you can also

'var' in dir(obj)

For example,

>>> class Something(object):
...     pass
...
>>> c = Something()
>>> c.a = 1
>>> 'a' in dir(c)
True
>>> 'b' in dir(c)
False

回答 5

我将假定该测试将在功能中使用,类似于user97370的答案。我不喜欢这个答案,因为它污染了全局命名空间。解决该问题的一种方法是改用类:

class InitMyVariable(object):
  my_variable = None

def __call__(self):
  if self.my_variable is None:
   self.my_variable = ...

我不喜欢这样,因为它使代码复杂化,并提出了一些问题,例如,是否应该确认Singleton编程模式?幸运的是,Python允许函数在一段时间内拥有属性,这为我们提供了一个简单的解决方案:

def InitMyVariable():
  if InitMyVariable.my_variable is None:
    InitMyVariable.my_variable = ...
InitMyVariable.my_variable = None

I will assume that the test is going to be used in a function, similar to user97370’s answer. I don’t like that answer because it pollutes the global namespace. One way to fix it is to use a class instead:

class InitMyVariable(object):
  my_variable = None

def __call__(self):
  if self.my_variable is None:
   self.my_variable = ...

I don’t like this, because it complicates the code and opens up questions such as, should this confirm to the Singleton programming pattern? Fortunately, Python has allowed functions to have attributes for a while, which gives us this simple solution:

def InitMyVariable():
  if InitMyVariable.my_variable is None:
    InitMyVariable.my_variable = ...
InitMyVariable.my_variable = None

回答 6

catchexcept在Python中被称为。除此之外,对于这种简单情况也很好。还有的AttributeError,可以用来检查一个对象具有的属性。

catch is called except in Python. other than that it’s fine for such simple cases. There’s the AttributeError that can be used to check if an object has an attribute.


回答 7

处理这种情况的一种通常有效的方法是不显式检查变量是否存在,而只是继续将可能不存在的变量的首次用法包装在try / except NameError中:

# Search for entry.
for x in y:
  if x == 3:
    found = x

# Work with found entry.
try:
  print('Found: {0}'.format(found))
except NameError:
  print('Not found')
else:
  # Handle rest of Found case here
  ...

A way that often works well for handling this kind of situation is to not explicitly check if the variable exists but just go ahead and wrap the first usage of the possibly non-existing variable in a try/except NameError:

# Search for entry.
for x in y:
  if x == 3:
    found = x

# Work with found entry.
try:
  print('Found: {0}'.format(found))
except NameError:
  print('Not found')
else:
  # Handle rest of Found case here
  ...

回答 8

我创建了一个自定义函数。

def exists(var):
     var_exists = var in locals() or var in globals()
     return var_exists

然后调用如下函数,将其替换variable_name为要检查的变量:

exists("variable_name")

将返回TrueFalse

I created a custom function.

def exists(var):
     var_exists = var in locals() or var in globals()
     return var_exists

Then the call the function like follows replacing variable_name with the variable you want to check:

exists("variable_name")

Will return True or False


Python中变量和函数名称的命名约定是什么?

问题:Python中变量和函数名称的命名约定是什么?

来自C#背景的变量和方法名称的命名约定通常为camelCase或PascalCase:

// C# example
string thisIsMyVariable = "a"
public void ThisIsMyMethod()

在Python中,我已经看到了上述内容,但也看到了使用下划线的情况:

# python example
this_is_my_variable = 'a'
def this_is_my_function():

有没有更优选的,确定的Python编码风格?

Coming from a C# background the naming convention for variables and method names are usually either camelCase or PascalCase:

// C# example
string thisIsMyVariable = "a"
public void ThisIsMyMethod()

In Python, I have seen the above but I have also seen underscores being used:

# python example
this_is_my_variable = 'a'
def this_is_my_function():

Is there a more preferable, definitive coding style for Python?


回答 0

请参阅Python PEP 8:函数和变量名称

函数名称应小写,必要时用下划线分隔单词,以提高可读性。

变量名遵循与函数名相同的约定。

仅在已经是主流样式(例如threading.py)的上下文中才允许使用blendCase,以保持向后兼容性。

See Python PEP 8: Function and Variable Names:

Function names should be lowercase, with words separated by underscores as necessary to improve readability.

Variable names follow the same convention as function names.

mixedCase is allowed only in contexts where that’s already the prevailing style (e.g. threading.py), to retain backwards compatibility.


回答 1

Google Python样式指南》具有以下约定:

module_namepackage_nameClassNamemethod_nameExceptionNamefunction_nameGLOBAL_CONSTANT_NAMEglobal_var_nameinstance_var_namefunction_parameter_namelocal_var_name

类似的命名方案应适用于 CLASS_CONSTANT_NAME

The Google Python Style Guide has the following convention:

module_name, package_name, ClassName, method_name, ExceptionName, function_name, GLOBAL_CONSTANT_NAME, global_var_name, instance_var_name, function_parameter_name, local_var_name.

A similar naming scheme should be applied to a CLASS_CONSTANT_NAME


回答 2

大卫·Goodger(在“代码就像Pythonista” 在这里)描述了PEP 8项建议如下:

  • joined_lower 用于函数,方法,属性,变量

  • joined_lowerALL_CAPS常量

  • StudlyCaps 上课

  • camelCase 仅符合先前的约定

David Goodger (in “Code Like a Pythonista” here) describes the PEP 8 recommendations as follows:

  • joined_lower for functions, methods, attributes, variables

  • joined_lower or ALL_CAPS for constants

  • StudlyCaps for classes

  • camelCase only to conform to pre-existing conventions


回答 3

正如Python代码样式指南所承认的那样,

Python库的命名约定有些混乱,因此我们永远都无法做到这一点

请注意,这仅指Python的标准库。如果他们不能得到那个一致,那么就几乎是具有很大的希望通常附着到约定所有的 Python代码,不是吗?

因此,在这里的讨论中,我可以推断出,如果在过渡到Python时继续使用变量或函数的Java或C#命名惯例(例如清晰明确的命名规则),这并不是一个可怕的罪过。当然,请记住,最好遵守代码库/项目/团队的流行风格。正如《 Python风格指南》指出的那样,内部一致性最重要。

随意将我视为异端。:-)像OP一样,我也不是“ Pythonista”,无论如何也没有。

As the Style Guide for Python Code admits,

The naming conventions of Python’s library are a bit of a mess, so we’ll never get this completely consistent

Note that this refers just to Python’s standard library. If they can’t get that consistent, then there hardly is much hope of having a generally-adhered-to convention for all Python code, is there?

From that, and the discussion here, I would deduce that it’s not a horrible sin if one keeps using e.g. Java’s or C#’s (clear and well-established) naming conventions for variables and functions when crossing over to Python. Keeping in mind, of course, that it is best to abide with whatever the prevailing style for a codebase / project / team happens to be. As the Python Style Guide points out, internal consistency matters most.

Feel free to dismiss me as a heretic. :-) Like the OP, I’m not a “Pythonista”, not yet anyway.


回答 4

如其他答案所示,有PEP 8,但是PEP 8只是标准库的样式指南,在其中仅作为福音。PEP 8对于其他代码段最常见的偏差之一是变量命名,尤其是方法。尽管考虑到使用mixedCase的代码量很大,但没有单一的主导风格,如果要进行严格的普查,则可能最终会得到带有mixedCase的PEP 8版本。与PEP 8几乎没有其他偏差是很常见的。

There is PEP 8, as other answers show, but PEP 8 is only the styleguide for the standard library, and it’s only taken as gospel therein. One of the most frequent deviations of PEP 8 for other pieces of code is the variable naming, specifically for methods. There is no single predominate style, although considering the volume of code that uses mixedCase, if one were to make a strict census one would probably end up with a version of PEP 8 with mixedCase. There is little other deviation from PEP 8 that is quite as common.


回答 5

如前所述,PEP 8表示可lower_case_with_underscores用于变量,方法和函数。

我更喜欢使用lower_case_with_underscores变量以及mixedCase方法和函数使代码更明确和可读。因此,遵循Python Zen的 “显式优于隐式”和“可读性”

As mentioned, PEP 8 says to use lower_case_with_underscores for variables, methods and functions.

I prefer using lower_case_with_underscores for variables and mixedCase for methods and functions makes the code more explicit and readable. Thus following the Zen of Python’s “explicit is better than implicit” and “Readability counts”


回答 6

@JohnTESlade回答的内容更进一步。Google的python样式指南提供了一些非常简洁的建议,

避免使用的名称

  • 单个字符名称(计数器或迭代器除外)
  • 任何程序包/模块名称中的破折号(-)
  • \__double_leading_and_trailing_underscore__ names (由Python保留)

命名约定

  • “内部”是指模块内部或类中受保护或私有的内部。
  • 在单个下划线(_)前面有一些支持来保护模块变量和函数(import * from中不包括)。在实例变量或方法前加双下划线(__)可以有效地使变量或方法对其类具有私有性(使用名称修饰)。
  • 将相关的类和顶级功能放到一个模块中。与Java不同,不需要将自己限制为每个模块一个类。
  • 使用CapWords类的名字,但lower_with_under.py对模块名称。尽管有许多命名的现有模块CapWords.py,但现在不建议这样做,因为当碰巧以一个类命名该模块时会造成混淆。(“等待-我写import StringIO还是写from StringIO import StringIO?”)

源自Guido建议的指南

further to what @JohnTESlade has answered. Google’s python style guide has some pretty neat recommendations,

Names to Avoid

  • single character names except for counters or iterators
  • dashes (-) in any package/module name
  • \__double_leading_and_trailing_underscore__ names (reserved by Python)

Naming Convention

  • “Internal” means internal to a module or protected or private within a class.
  • Prepending a single underscore (_) has some support for protecting module variables and functions (not included with import * from). Prepending a double underscore (__) to an instance variable or method effectively serves to make the variable or method private to its class (using name mangling).
  • Place related classes and top-level functions together in a module. Unlike Java, there is no need to limit yourself to one class per module.
  • Use CapWords for class names, but lower_with_under.py for module names. Although there are many existing modules named CapWords.py, this is now discouraged because it’s confusing when the module happens to be named after a class. (“wait — did I write import StringIO or from StringIO import StringIO?”)

Guidelines derived from Guido’s Recommendations


回答 7

大多数python的人都喜欢使用下划线,但是自从5年前以来,即使我使用python,我仍然不喜欢它们。它们对我来说看起来很难看,但也许这就是我脑海中的所有Java。

我只是喜欢驼峰更好,因为它适合与类的命名方式更好,感觉更符合逻辑具有SomeClass.doSomething()SomeClass.do_something()。如果您在python中查看全局模块索引,则会发现这两者,这是因为它是随着时间的推移而增长的各种来源的库的集合,而不是由像Sun这样的公司开发的具有严格编码规则的库。我要说的底线是:使用任何您喜欢的更好的东西,这只是个人品味的问题。

Most python people prefer underscores, but even I am using python since more than 5 years right now, I still do not like them. They just look ugly to me, but maybe that’s all the Java in my head.

I simply like CamelCase better since it fits better with the way classes are named, It feels more logical to have SomeClass.doSomething() than SomeClass.do_something(). If you look around in the global module index in python, you will find both, which is due to the fact that it’s a collection of libraries from various sources that grew overtime and not something that was developed by one company like Sun with strict coding rules. I would say the bottom line is: Use whatever you like better, it’s just a question of personal taste.


回答 8

我个人尝试将CamelCase用于类,mixedCase方法和函数。变量通常用下划线分隔(当我记得时)。这样一来,我就可以一目了然地告诉我我到底在叫什么,而不是所有看起来都一样的东西。

Personally I try to use CamelCase for classes, mixedCase methods and functions. Variables are usually underscore separated (when I can remember). This way I can tell at a glance what exactly I’m calling, rather than everything looking the same.


回答 9

有一篇关于此的论文:http : //www.cs.kent.edu/~jmaletic/papers/ICPC2010-CamelCaseUnderScoreClouds.pdf

TL; DR它说snake_case比camelCase更具可读性。这就是为什么现代语言在任何可能的地方使用(或应该使用)蛇的原因。

There is a paper about this: http://www.cs.kent.edu/~jmaletic/papers/ICPC2010-CamelCaseUnderScoreClouds.pdf

TL;DR It says that snake_case is more readable than camelCase. That’s why modern languages use (or should use) snake wherever they can.


回答 10

编码风格通常是组织内部政策/惯例标准的一部分,但我认为一般来说,all_lower_case_underscore_separator风格(也称为snake_case)在python中最为常见。

The coding style is usually part of an organization’s internal policy/convention standards, but I think in general, the all_lower_case_underscore_separator style (also called snake_case) is most common in python.


回答 11

在以其他编程语言进行开发时,我个人使用Java的命名约定,因为它一致且易于遵循。这样,我就不会一直在努力使用哪些约定不应该成为我项目中最难的部分!

I personally use Java’s naming conventions when developing in other programming languages as it is consistent and easy to follow. That way I am not continuously struggling over what conventions to use which shouldn’t be the hardest part of my project!


回答 12

通常,遵循语言标准库中使用的约定。

Typically, one follow the conventions used in the language’s standard library.


如何检查变量的类型是否为字符串?

问题:如何检查变量的类型是否为字符串?

有没有一种方法可以检查python中变量的类型是否为string,例如:

isinstance(x,int);

对于整数值?

Is there a way to check if the type of a variable in python is a string, like:

isinstance(x,int);

for integer values?


回答 0

在Python 2.x中,您可以

isinstance(s, basestring)

basestring抽象的超类strunicode。它可用于测试对象是否是str或的实例unicode


在Python 3.x中,正确的测试是

isinstance(s, str)

bytes在Python 3中,该类不被视为字符串类型。

In Python 2.x, you would do

isinstance(s, basestring)

basestring is the abstract superclass of str and unicode. It can be used to test whether an object is an instance of str or unicode.


In Python 3.x, the correct test is

isinstance(s, str)

The bytes class isn’t considered a string type in Python 3.


回答 1

我知道这是一个古老的话题,但是作为第一个显示在google上的话题,鉴于我没有找到满意的答案,因此我将其留在此处以供将来参考:

第六个是Python 2和3兼容性库,它已经解决了这个问题。然后,您可以执行以下操作:

import six

if isinstance(value, six.string_types):
    pass # It's a string !!

检查代码,您会发现:

import sys

PY3 = sys.version_info[0] == 3

if PY3:
    string_types = str,
else:
    string_types = basestring,

I know this is an old topic, but being the first one shown on google and given that I don’t find any of the answers satisfactory, I’ll leave this here for future reference:

six is a Python 2 and 3 compatibility library which already covers this issue. You can then do something like this:

import six

if isinstance(value, six.string_types):
    pass # It's a string !!

Inspecting the code, this is what you find:

import sys

PY3 = sys.version_info[0] == 3

if PY3:
    string_types = str,
else:
    string_types = basestring,

回答 2

在Python 3.x或Python 2.7.6中

if type(x) == str:

In Python 3.x or Python 2.7.6

if type(x) == str:

回答 3

你可以做:

var = 1
if type(var) == int:
   print('your variable is an integer')

要么:

var2 = 'this is variable #2'
if type(var2) == str:
    print('your variable is a string')
else:
    print('your variable IS NOT a string')

希望这可以帮助!

you can do:

var = 1
if type(var) == int:
   print('your variable is an integer')

or:

var2 = 'this is variable #2'
if type(var2) == str:
    print('your variable is a string')
else:
    print('your variable IS NOT a string')

hope this helps!


回答 4

如果要检查的内容多于整数和字符串,则类型模块也存在。 http://docs.python.org/library/types.html

The type module also exists if you are checking more than ints and strings. http://docs.python.org/library/types.html


回答 5

根据以下更好的答案进行编辑。记下3个答案,找出基弦的凉爽。

旧答案:当心unicode字符串,您可以从多个地方获得unicode字符串,包括Windows中的所有COM调用。

if isinstance(target, str) or isinstance(target, unicode):

Edit based on better answer below. Go down about 3 answers and find out about the coolness of basestring.

Old answer: Watch out for unicode strings, which you can get from several places, including all COM calls in Windows.

if isinstance(target, str) or isinstance(target, unicode):

回答 6

由于basestring未在Python3中定义,因此此小技巧可能有助于使代码兼容:

try: # check whether python knows about 'basestring'
   basestring
except NameError: # no, it doesn't (it's Python3); use 'str' instead
   basestring=str

之后,您可以在Python2和Python3上运行以下测试

isinstance(myvar, basestring)

since basestring isn’t defined in Python3, this little trick might help to make the code compatible:

try: # check whether python knows about 'basestring'
   basestring
except NameError: # no, it doesn't (it's Python3); use 'str' instead
   basestring=str

after that you can run the following test on both Python2 and Python3

isinstance(myvar, basestring)

回答 7

Python 2/3包括unicode

from __future__ import unicode_literals
from builtins import str  #  pip install future
isinstance('asdf', str)   #  True
isinstance(u'asdf', str)  #  True

http://python-future.org/overview.html

Python 2 / 3 including unicode

from __future__ import unicode_literals
from builtins import str  #  pip install future
isinstance('asdf', str)   #  True
isinstance(u'asdf', str)  #  True

http://python-future.org/overview.html


回答 8

我还要注意,如果要检查变量的类型是否为特定类型,可以将变量的类型与已知对象的类型进行比较。

对于字符串,您可以使用此

type(s) == type('')

Also I want notice that if you want to check whether the type of a variable is a specific kind, you can compare the type of the variable to the type of a known object.

For string you can use this

type(s) == type('')

回答 9

其他人在这里提供了很多好的建议,但是我看不到一个很好的跨平台摘要。对于任何Python程序来说,以下内容都是不错的选择:

def isstring(s):
    # if we use Python 3
    if (sys.version_info[0] >= 3):
        return isinstance(s, str)
    # we use Python 2
    return isinstance(s, basestring)

在此函数中,我们用于isinstance(object, classinfo)查看输入是str在Python 3中还是basestring在Python 2中。

Lots of good suggestions provided by others here, but I don’t see a good cross-platform summary. The following should be a good drop in for any Python program:

def isstring(s):
    # if we use Python 3
    if (sys.version_info[0] >= 3):
        return isinstance(s, str)
    # we use Python 2
    return isinstance(s, basestring)

In this function, we use isinstance(object, classinfo) to see if our input is a str in Python 3 or a basestring in Python 2.


回答 10

不使用basestring的Python 2替代方法:

isinstance(s, (str, unicode))

但由于unicode未定义(在Python 3中),因此在Python 3中仍然无法使用。

Alternative way for Python 2, without using basestring:

isinstance(s, (str, unicode))

But still won’t work in Python 3 since unicode isn’t defined (in Python 3).


回答 11

所以,

您可以使用很多选项来检查变量是否为字符串:

a = "my string"
type(a) == str # first 
a.__class__ == str # second
isinstance(a, str) # third
str(a) == a # forth
type(a) == type('') # fifth

此命令是有目的的。

So,

You have plenty of options to check whether your variable is string or not:

a = "my string"
type(a) == str # first 
a.__class__ == str # second
isinstance(a, str) # third
str(a) == a # forth
type(a) == type('') # fifth

This order is for purpose.


回答 12

a = '1000' # also tested for 'abc100', 'a100bc', '100abc'

isinstance(a, str) or isinstance(a, unicode)

返回True

type(a) in [str, unicode]

返回True

a = '1000' # also tested for 'abc100', 'a100bc', '100abc'

isinstance(a, str) or isinstance(a, unicode)

returns True

type(a) in [str, unicode]

returns True


回答 13

这是我对同时支持Python 2和Python 3以及这些要求的回答:

  • 用最少的Py2兼容代码以Py3代码编写。
  • 稍后删除Py2兼容代码而不会受到干扰。即仅旨在删除,不修改Py3代码。
  • 避免使用 six或类似的compat模块,因为它们倾向于隐藏试图实现的目标。
  • 面向未来的潜在Py4。

import sys
PY2 = sys.version_info.major == 2

# Check if string (lenient for byte-strings on Py2):
isinstance('abc', basestring if PY2 else str)

# Check if strictly a string (unicode-string):
isinstance('abc', unicode if PY2 else str)

# Check if either string (unicode-string) or byte-string:
isinstance('abc', basestring if PY2 else (str, bytes))

# Check for byte-string (Py3 and Py2.7):
isinstance('abc', bytes)

Here is my answer to support both Python 2 and Python 3 along with these requirements:

  • Written in Py3 code with minimal Py2 compat code.
  • Remove Py2 compat code later without disruption. I.e. aim for deletion only, no modification to Py3 code.
  • Avoid using six or similar compat module as they tend to hide away what is trying to be achieved.
  • Future-proof for a potential Py4.

import sys
PY2 = sys.version_info.major == 2

# Check if string (lenient for byte-strings on Py2):
isinstance('abc', basestring if PY2 else str)

# Check if strictly a string (unicode-string):
isinstance('abc', unicode if PY2 else str)

# Check if either string (unicode-string) or byte-string:
isinstance('abc', basestring if PY2 else (str, bytes))

# Check for byte-string (Py3 and Py2.7):
isinstance('abc', bytes)

回答 14

如果您不想依赖外部库,那么这对于Python 2.7+和Python 3(http://ideone.com/uB4Kdc)都适用:

# your code goes here
s = ["test"];
#s = "test";
isString = False;

if(isinstance(s, str)):
    isString = True;
try:
    if(isinstance(s, basestring)):
        isString = True;
except NameError:
    pass;

if(isString):
    print("String");
else:
    print("Not String");

If you do not want to depend on external libs, this works both for Python 2.7+ and Python 3 (http://ideone.com/uB4Kdc):

# your code goes here
s = ["test"];
#s = "test";
isString = False;

if(isinstance(s, str)):
    isString = True;
try:
    if(isinstance(s, basestring)):
        isString = True;
except NameError:
    pass;

if(isString):
    print("String");
else:
    print("Not String");

回答 15

您可以简单地使用isinstance函数来确保输入数据的格式为stringunicode。以下示例将帮助您轻松理解。

>>> isinstance('my string', str)
True
>>> isinstance(12, str)
False
>>> isinstance('my string', unicode)
False
>>> isinstance(u'my string',  unicode)
True

You can simply use the isinstance function to make sure that the input data is of format string or unicode. Below examples will help you to understand easily.

>>> isinstance('my string', str)
True
>>> isinstance(12, str)
False
>>> isinstance('my string', unicode)
False
>>> isinstance(u'my string',  unicode)
True

回答 16

s = '123'
issubclass(s.__class__, str)
s = '123'
issubclass(s.__class__, str)

回答 17

这是我的方法:

if type(x) == type(str()):

This is how I do it:

if type(x) == type(str()):

回答 18

我见过:

hasattr(s, 'endswith') 

I’ve seen:

hasattr(s, 'endswith') 

回答 19

>>> thing = 'foo'
>>> type(thing).__name__ == 'str' or type(thing).__name__ == 'unicode'
True
>>> thing = 'foo'
>>> type(thing).__name__ == 'str' or type(thing).__name__ == 'unicode'
True