标签归档:tabs

如何在Python中编写“标签”?

问题:如何在Python中编写“标签”?

假设我有一个文件。如何写“你好” TAB“ alex”?

Let’s say I have a file. How do I write “hello” TAB “alex”?


回答 0

这是代码:

f = open(filename, 'w')
f.write("hello\talex")

\t字符串的内部是水平制表符的转义序列。

This is the code:

f = open(filename, 'w')
f.write("hello\talex")

The \t inside the string is the escape sequence for the horizontal tabulation.


回答 1

Python 参考手册包括几个可以在字符串中使用的字符串文字。这些特殊的字符序列被转义序列的预期含义代替。

这是一些更有用的转义序列的表格,并描述了它们的输出。

Escape Sequence       Meaning
\t                    Tab
\\                    Inserts a back slash (\)
\'                    Inserts a single quote (')
\"                    Inserts a double quote (")
\n                    Inserts a ASCII Linefeed (a new line)

基本范例

如果我想打印一些由制表符分隔的数据点,则可以打印此字符串。

DataString = "0\t12\t24"
print (DataString)

退货

0    12    24

清单范例

这是另一个示例,其中我们正在打印列表项,并且希望通过TAB来分隔项目。

DataPoints = [0,12,24]
print (str(DataPoints[0]) + "\t" + str(DataPoints[1]) + "\t" + str(DataPoints[2]))

退货

0    12    24

原始字符串

请注意,原始字符串(包含前缀“ r”的字符串),字符串文字将被忽略。这允许将这些特殊字符序列包含在字符串中而无需更改。

DataString = r"0\t12\t24"
print (DataString)

退货

0\t12\t24

这可能是不希望的输出

弦长

还应注意,字符串文字长度仅为一个字符。

DataString = "0\t12\t24"
print (len(DataString))

退货

7

原始字符串的长度为9。

The Python reference manual includes several string literals that can be used in a string. These special sequences of characters are replaced by the intended meaning of the escape sequence.

Here is a table of some of the more useful escape sequences and a description of the output from them.

Escape Sequence       Meaning
\t                    Tab
\\                    Inserts a back slash (\)
\'                    Inserts a single quote (')
\"                    Inserts a double quote (")
\n                    Inserts a ASCII Linefeed (a new line)

Basic Example

If i wanted to print some data points separated by a tab space I could print this string.

DataString = "0\t12\t24"
print (DataString)

Returns

0    12    24

Example for Lists

Here is another example where we are printing the items of list and we want to sperate the items by a TAB.

DataPoints = [0,12,24]
print (str(DataPoints[0]) + "\t" + str(DataPoints[1]) + "\t" + str(DataPoints[2]))

Returns

0    12    24

Raw Strings

Note that raw strings (a string which include a prefix “r”), string literals will be ignored. This allows these special sequences of characters to be included in strings without being changed.

DataString = r"0\t12\t24"
print (DataString)

Returns

0\t12\t24

Which maybe an undesired output

String Lengths

It should also be noted that string literals are only one character in length.

DataString = "0\t12\t24"
print (len(DataString))

Returns

7

The raw string has a length of 9.


回答 2

您可以在字符串文字中使用\ t:

"hello\talex"

You can use \t in a string literal:

"hello\talex"


回答 3

它通常\t在命令行界面中,它将把char \t转换为空白制表符。

例如,hello\talex-> hello--->alex

It’s usually \t in command-line interfaces, which will convert the char \t into the whitespace tab character.

For example, hello\talex -> hello--->alex.


回答 4

正如未在任何答案中提到的那样,以防万一您想要对齐和间隔文本时,可以使用字符串格式功能。(在python 2.5之上)当然\t是一个TAB令牌,而所描述的方法会生成空格。

例:

print "{0:30} {1}".format("hi", "yes")
> hi                             yes

另一个示例,左对齐:

print("{0:<10} {1:<10} {2:<10}".format(1.0, 2.2, 4.4))
>1.0        2.2        4.4 

As it wasn’t mentioned in any answers, just in case you want to align and space your text, you can use the string format features. (above python 2.5) Of course \t is actually a TAB token whereas the described method generates spaces.

Example:

print "{0:30} {1}".format("hi", "yes")
> hi                             yes

Another Example, left aligned:

print("{0:<10} {1:<10} {2:<10}".format(1.0, 2.2, 4.4))
>1.0        2.2        4.4 

回答 5

以下是一些获取“ hello” TAB“ alex”(使用Python 3.6.10测试)的更奇特的Python 3方法:

"hello\N{TAB}alex"

"hello\N{tab}alex"

"hello\N{TaB}alex"

"hello\N{HT}alex"

"hello\N{CHARACTER TABULATION}alex"

"hello\N{HORIZONTAL TABULATION}alex"

"hello\x09alex"

"hello\u0009alex"

"hello\U00000009alex"

实际上,代替使用转义序列,可以将制表符直接插入字符串文字中。这是带有制表符的代码,可用于复制和尝试:

"hello alex"

如果在复制字符串期间在上方字符串中的选项卡不会丢失,则“ print(repr(<上方字符串>)”应打印’hello \ talex’。

请参阅相应的Python文档以获取参考。

Here are some more exotic Python 3 ways to get “hello” TAB “alex” (tested with Python 3.6.10):

"hello\N{TAB}alex"

"hello\N{tab}alex"

"hello\N{TaB}alex"

"hello\N{HT}alex"

"hello\N{CHARACTER TABULATION}alex"

"hello\N{HORIZONTAL TABULATION}alex"

"hello\x09alex"

"hello\u0009alex"

"hello\U00000009alex"

Actually, instead of using an escape sequence, it is possible to insert tab symbol directly into the string literal. Here is the code with a tabulation character to copy and try:

"hello alex"

If the tab in the string above won’t be lost anywhere during copying the string then “print(repr(< string from above >)” should print ‘hello\talex’.

See respective Python documentation for reference.


如何在Python中检查文本是否为“空”(空格,制表符,换行符)?

问题:如何在Python中检查文本是否为“空”(空格,制表符,换行符)?

如何在Python中测试字符串是否为空?

例如,

"<space><space><space>" 是空的,所以是

"<space><tab><space><newline><space>",也是

"<newline><newline><newline><tab><newline>"

How can I test if a string contains only whitespace?

Example strings:

  • " " (space, space, space)

  • " \t \n " (space, tab, space, newline, space)

  • "\n\n\n\t\n" (newline, newline, newline, tab, newline)


回答 0

yourString.isspace()

“如果字符串中只有空格字符并且至少有一个字符,则返回true,否则返回false。”

结合特殊情况处理空字符串。

或者,您可以使用

strippedString = yourString.strip()

然后检查strippedString是否为空。

Use the str.isspace() method:

Return True if there are only whitespace characters in the string and there is at least one character, False otherwise.

A character is whitespace if in the Unicode character database (see unicodedata), either its general category is Zs (“Separator, space”), or its bidirectional class is one of WS, B, or S.

Combine that with a special case for handling the empty string.

Alternatively, you could use str.strip() and check if the result is empty.


回答 1

>>> tests = ['foo', ' ', '\r\n\t', '', None]
>>> [bool(not s or s.isspace()) for s in tests]
[False, True, True, True, True]
>>>
>>> tests = ['foo', ' ', '\r\n\t', '', None]
>>> [not s or s.isspace() for s in tests]
[False, True, True, True, True]

回答 2

您要使用的isspace()方法

海峡 isspace()

如果字符串中只有空格字符并且至少有一个字符,则返回true,否则返回false。

这是在每个字符串对象上定义的。这是您的特定用例的用法示例:

if aStr and (not aStr.isspace()):
    print aStr

You want to use the isspace() method

str.isspace()

Return true if there are only whitespace characters in the string and there is at least one character, false otherwise.

That’s defined on every string object. Here it is an usage example for your specific use case:

if aStr and (not aStr.isspace()):
    print aStr

回答 3

You can use the str.isspace() method.


回答 4

对于那些希望像Apache StringUtils.isBlank或Guava Strings.isNullOrEmpty这样的行为的用户:

if mystring and mystring.strip():
    print "not blank string"
else:
    print "blank string"

for those who expect a behaviour like the apache StringUtils.isBlank or Guava Strings.isNullOrEmpty :

if mystring and mystring.strip():
    print "not blank string"
else:
    print "blank string"

回答 5

检查split()方法给定的列表的长度。

if len(your_string.split()==0:
     print("yes")

或者将strip()方法的输出与null进行比较。

if your_string.strip() == '':
     print("yes")

Check the length of the list given by of split() method.

if len(your_string.split()==0:
     print("yes")

Or Compare output of strip() method with null.

if your_string.strip() == '':
     print("yes")

回答 6

这是在所有情况下都适用的答案:

def is_empty(s):
    "Check whether a string is empty"
    return not s or not s.strip()

如果变量为None,它将在处停止not s并且不再进行评估(因为not None == True)。显然,该strip()方法可以处理tab,换行符等常见情况。

Here is an answer that should work in all cases:

def is_empty(s):
    "Check whether a string is empty"
    return not s or not s.strip()

If the variable is None, it will stop at not sand not evaluate further (since not None == True). Apparently, the strip()method takes care of the usual cases of tab, newline, etc.


回答 7

我假设在您的情况下,空字符串是真正为空的字符串或包含所有空白的字符串。

if(str.strip()):
    print("string is not empty")
else:
    print("string is empty")

请注意,这不会检查 None

I’m assuming in your scenario, an empty string is a string that is truly empty or one that contains all white space.

if(str.strip()):
    print("string is not empty")
else:
    print("string is empty")

Note this does not check for None


回答 8

我使用以下内容:

if str and not str.isspace():
  print('not null and not empty nor whitespace')
else:
  print('null or empty or whitespace')

I used following:

if str and not str.isspace():
  print('not null and not empty nor whitespace')
else:
  print('null or empty or whitespace')

回答 9

检查字符串只是空格还是换行符

使用这个简单的代码

mystr = "      \n  \r  \t   "
if not mystr.strip(): # The String Is Only Spaces!
    print("\n[!] Invalid String !!!")
    exit(1)
mystr = mystr.strip()
print("\n[*] Your String Is: "+mystr)

To check if a string is just a spaces or newline

Use this simple code

mystr = "      \n  \r  \t   "
if not mystr.strip(): # The String Is Only Spaces!
    print("\n[!] Invalid String !!!")
    exit(1)
mystr = mystr.strip()
print("\n[*] Your String Is: "+mystr)

回答 10

与c#字符串静态方法类似isNullOrWhiteSpace。

def isNullOrWhiteSpace(str):
  """Indicates whether the specified string is null or empty string.
     Returns: True if the str parameter is null, an empty string ("") or contains 
     whitespace. Returns false otherwise."""
  if (str is None) or (str == "") or (str.isspace()):
    return True
  return False

isNullOrWhiteSpace(None) -> True // None equals null in c#, java, php
isNullOrWhiteSpace("")   -> True
isNullOrWhiteSpace(" ")  -> True

Resemblence with c# string static method isNullOrWhiteSpace.

def isNullOrWhiteSpace(str):
  """Indicates whether the specified string is null or empty string.
     Returns: True if the str parameter is null, an empty string ("") or contains 
     whitespace. Returns false otherwise."""
  if (str is None) or (str == "") or (str.isspace()):
    return True
  return False

isNullOrWhiteSpace(None) -> True // None equals null in c#, java, php
isNullOrWhiteSpace("")   -> True
isNullOrWhiteSpace(" ")  -> True