标签归档:newline

如何在f字符串中使用换行符’\ n’格式化Python 3.6中的输出?

问题:如何在f字符串中使用换行符’\ n’格式化Python 3.6中的输出?

我想知道如何用f字符串以Pythonic方式格式化这种情况:

names = ['Adam', 'Bob', 'Cyril']
text = f"Winners are:\n{'\n'.join(names)}"
print(text)

问题是'\'无法在{...}f字符串的表达式部分内使用。预期Yield:

Winners are:
Adam
Bob
Cyril

I would like to know how to format this case in a Pythonic way with f-strings:

names = ['Adam', 'Bob', 'Cyril']
text = f"Winners are:\n{'\n'.join(names)}"
print(text)

The problem is that '\' cannot be used inside the {...} expression portions of an f-string. Expected output:

Winners are:
Adam
Bob
Cyril

回答 0

你不能 反斜杠不能出现在花括号内{};这样做会导致SyntaxError

>>> f'{\}'
SyntaxError: f-string expression part cannot include a backslash

这是在PEP中为f字符串指定的:

反斜杠可能不会出现在f字符串的表达式部分内,[…]

一种选择是先'\n'命名,然后再.joinf-string 内进行命名;也就是说,不使用文字:

names = ['Adam', 'Bob', 'Cyril']
nl = '\n'
text = f"Winners are:{nl}{nl.join(names)}"
print(text)

结果是:

Winners are:
Adam
Bob
Cyril

@wim指定的另一个选项是chr(10)用来获取\n返回值,然后在该处加入。f"Winners are:\n{chr(10).join(names)}"

当然,还有另一种方法是'\n'.join预先添加相应的名称:

n = "\n".join(names)
text = f"Winners are:\n{n}"

结果相同。

注意:

这是f-string和之间的细微差别之一str.format。在后者中,您可以始终使用标点符号,只要打开包含这些键的相应古怪字典即可:

>>> "{\\} {*}".format(**{"\\": 'Hello', "*": 'World!'})
"Hello World!"

(请不要这样做。)

在前一种情况下,标点符号是不允许的,因为您不能使用它们的标识符。


撇开:我肯定会选择printformat,因为其他答案也可以替代。我给出的选项仅在由于某些原因必须使用f字符串的情况下适用。

仅仅因为有些新事物,并不意味着您应该尝试用它做一切;-)

You can’t. Backslashes cannot appear inside the curly braces {}; doing so results in a SyntaxError:

>>> f'{\}'
SyntaxError: f-string expression part cannot include a backslash

This is specified in the PEP for f-strings:

Backslashes may not appear inside the expression portions of f-strings, […]

One option is assinging '\n' to a name and then .join on that inside the f-string; that is, without using a literal:

names = ['Adam', 'Bob', 'Cyril']
nl = '\n'
text = f"Winners are:{nl}{nl.join(names)}"
print(text)

Results in:

Winners are:
Adam
Bob
Cyril

Another option, as specified by @wim, is to use chr(10) to get \n returned and then join there. f"Winners are:\n{chr(10).join(names)}"

Yet another, of course, is to '\n'.join beforehand and then add the name accordingly:

n = "\n".join(names)
text = f"Winners are:\n{n}"

which results in the same output.

Note:

This is one of the small differences between f-strings and str.format. In the latter, you can always use punctuation granted that a corresponding wacky dict is unpacked that contains those keys:

>>> "{\\} {*}".format(**{"\\": 'Hello', "*": 'World!'})
"Hello World!"

(Please don’t do this.)

In the former, punctuation isn’t allowed because you can’t have identifiers that use them.


Aside: I would definitely opt for print or format, as the other answers suggest as an alternative. The options I’ve given only apply if you must for some reason use f-strings.

Just because something is new, doesn’t mean you should try and do everything with it ;-)


回答 1

您不需要f字符串或其他格式化程序即可使用分隔符打印字符串列表。只需使用sep关键字参数即可print()

names = ['Adam', 'Bob', 'Cyril']
print('Winners are:', *names, sep='\n')

输出:

Winners are:
Adam
Bob
Cyril

就是说,使用str.join()/str.format()这里比任何f字符串解决方法更容易理解。

print('\n'.join(['Winners are:', *names]))
print('Winners are:\n{}'.format('\n'.join(names)))

You don’t need f-strings or other formatters to print a list of strings with a separator. Just use the sep keyword argument to print():

names = ['Adam', 'Bob', 'Cyril']
print('Winners are:', *names, sep='\n')

Output:

Winners are:
Adam
Bob
Cyril

That said, using str.join()/str.format() here would arguably be simpler and more readable than any f-string workaround:

print('\n'.join(['Winners are:', *names]))
print('Winners are:\n{}'.format('\n'.join(names)))

回答 2

您不能像其他人所说的那样在f字符串中使用反斜杠,但是您可以使用来解决这个问题os.linesep(尽管请注意,并非\n在所有平台上都使用反斜杠,除非读/写二进制文件,否则不建议这样做;请参阅Rick的评论):

>>> import os
>>> names = ['Adam', 'Bob', 'Cyril']
>>> print(f"Winners are:\n{os.linesep.join(names)}")
Winners are:
Adam
Bob
Cyril 

或以一种不太易读的方式,但保证是\n,方法是chr()

>>> print(f"Winners are:\n{chr(10).join(names)}")
Winners are:
Adam
Bob
Cyril

You can’t use backslashes in f-strings as others have said, but you could step around this using os.linesep (although note this won’t be \n on all platforms, and is not recommended unless reading/writing binary files; see Rick’s comments):

>>> import os
>>> names = ['Adam', 'Bob', 'Cyril']
>>> print(f"Winners are:\n{os.linesep.join(names)}")
Winners are:
Adam
Bob
Cyril 

Or perhaps in a less readable way, but guaranteed to be \n, with chr():

>>> print(f"Winners are:\n{chr(10).join(names)}")
Winners are:
Adam
Bob
Cyril

回答 3

其他答案给出了有关如何将换行符放入f字符串字段的想法。但是,我认为对于OP给出的示例(可能指示OP的实际用例),实际上不应该使用这些想法。

使用f字符串的全部目的是提高代码的可读性。f字符串是您无法使用的format。请仔细考虑是否对此有更多可读性(如果可以的话):

f"Winners are:\n{'\n'.join(names)}"

…或这个:

newline = '\n'
f"Winners are:\n{newline.join(names)}"

…或这个:

"Winners are:\n{chr(10).join(names)}"

与这个:

"Winners are:\n{}".format('\n'.join(names))

最后一种方法至少具有可读性,如果不是更多的话。

简而言之:当您需要螺丝起子时,不要只用锤子,因为那是新的有光泽的工具。读取代码的频率远高于写入代码。

对于其他用例,是的,这个chr(10)想法或newline想法可能是适当的。但不是给定的。

The other answers give ideas for how to put the newline character into a f-string field. However, I would argue that for the example the OP gave (which may or may not be indicative of OP’s actual use case), none of these ideas should actually be used.

The entire point of using f-strings is increasing code readability. There is nothing you can do with f-strings that you cannot do with format. Consider carefully whether there is anything more readable about this (if you could do it):

f"Winners are:\n{'\n'.join(names)}"

…or this:

newline = '\n'
f"Winners are:\n{newline.join(names)}"

…or this:

"Winners are:\n{chr(10).join(names)}"

vs. this:

"Winners are:\n{}".format('\n'.join(names))

The last way is at least as readable, if not more so.

In short: don’t use a hammer when you need a screwdriver just because you have a shiny new one. Code is read much more often than it is written.

For other use cases, yes, it’s possible the chr(10) idea or newline idea may be appropriate. But not for the one given.


如何在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

每次在新行中将字符串写入文件

问题:每次在新行中将字符串写入文件

我想在每次调用时在字符串后添加换行符file.write()。在Python中最简单的方法是什么?

I want to append a newline to my string every time I call file.write(). What’s the easiest way to do this in Python?


回答 0

使用“ \ n”:

file.write("My String\n")

请参阅Python手册以获取参考。

Use “\n”:

file.write("My String\n")

See the Python manual for reference.


回答 1

您可以通过两种方式执行此操作:

f.write("text to write\n")

或者,取决于您的Python版本(2或3):

print >>f, "text to write"         # Python 2.x
print("text to write", file=f)     # Python 3.x

You can do this in two ways:

f.write("text to write\n")

or, depending on your Python version (2 or 3):

print >>f, "text to write"         # Python 2.x
print("text to write", file=f)     # Python 3.x

回答 2

您可以使用:

file.write(your_string + '\n')

You can use:

file.write(your_string + '\n')

回答 3

如果您广泛使用它(很多书面文字),则可以将’​​file’子类化:

class cfile(file):
    #subclass file to have a more convienient use of writeline
    def __init__(self, name, mode = 'r'):
        self = file.__init__(self, name, mode)

    def wl(self, string):
        self.writelines(string + '\n')

现在,它提供了一个附加功能wl,它可以执行您想要的操作:

fid = cfile('filename.txt', 'w')
fid.wl('appends newline charachter')
fid.wl('is written on a new line')
fid.close()

也许我缺少诸如不同的换行符(\ n,\ r,…)之类的东西,或者最后一行也以换行符结尾,但这对我有用。

If you use it extensively (a lot of written lines), you can subclass ‘file’:

class cfile(file):
    #subclass file to have a more convienient use of writeline
    def __init__(self, name, mode = 'r'):
        self = file.__init__(self, name, mode)

    def wl(self, string):
        self.writelines(string + '\n')

Now it offers an additional function wl that does what you want:

fid = cfile('filename.txt', 'w')
fid.wl('appends newline charachter')
fid.wl('is written on a new line')
fid.close()

Maybe I am missing something like different newline characters (\n, \r, …) or that the last line is also terminated with a newline, but it works for me.


回答 4

你可以做:

file.write(your_string + '\n')

正如另一个答案所建议的那样,但是为什么在您可以调用file.write两次时使用字符串连接(缓慢,容易出错):

file.write(your_string)
file.write("\n")

请注意,写操作是缓冲的,因此相当于同一件事。

you could do:

file.write(your_string + '\n')

as suggested by another answer, but why using string concatenation (slow, error-prone) when you can call file.write twice:

file.write(your_string)
file.write("\n")

note that writes are buffered so it amounts to the same thing.


回答 5

file_path = "/path/to/yourfile.txt"
with open(file_path, 'a') as file:
    file.write("This will be added to the next line\n")

要么

log_file = open('log.txt', 'a')
log_file.write("This will be added to the next line\n")
file_path = "/path/to/yourfile.txt"
with open(file_path, 'a') as file:
    file.write("This will be added to the next line\n")

or

log_file = open('log.txt', 'a')
log_file.write("This will be added to the next line\n")

回答 6

只是一个注释,file不受支持Python 3,已被删除。您可以使用open内置功能执行相同的操作。

f = open('test.txt', 'w')
f.write('test\n')

Just a note, file isn’t supported in Python 3 and was removed. You can do the same with the open built-in function.

f = open('test.txt', 'w')
f.write('test\n')

回答 7

除非写入二进制文件,否则请使用打印。下面的示例非常适合格式化csv文件:

def write_row(file_, *columns):
    print(*columns, sep='\t', end='\n', file=file_)

用法:

PHI = 45
with open('file.csv', 'a+') as f:
    write_row(f, 'header', 'phi:', PHI, 'serie no. 2')
    write_row(f)  # newline
    write_row(f, data[0], data[1])

笔记:

Unless write to binary files, use print. Below example good for formatting csv files:

def write_row(file_, *columns):
    print(*columns, sep='\t', end='\n', file=file_)

Usage:

PHI = 45
with open('file.csv', 'a+') as f:
    write_row(f, 'header', 'phi:', PHI, 'serie no. 2')
    write_row(f)  # newline
    write_row(f, data[0], data[1])

Notes:


回答 8

使用fstring从列表写入的另一种解决方案

lines = ['hello','world']
with open('filename.txt', "w") as fhandle:
  for line in lines:
    fhandle.write(f'{line}\n')

Another solution that writes from a list using fstring

lines = ['hello','world']
with open('filename.txt', "w") as fhandle:
  for line in lines:
    fhandle.write(f'{line}\n')

回答 9

这是我想出的解决方案,试图为自己解决此问题,以便系统地生成\ n作为分隔符。它使用字符串列表进行写入,其中每个字符串都是文件的一行,但是看来它也可能对您有用。(Python 3. +)

#Takes a list of strings and prints it to a file.
def writeFile(file, strList):
    line = 0
    lines = []
    while line < len(strList):
        lines.append(cheekyNew(line) + strList[line])
        line += 1
    file = open(file, "w")
    file.writelines(lines)
    file.close()

#Returns "\n" if the int entered isn't zero, otherwise "".
def cheekyNew(line):
    if line != 0:
        return "\n"
    return ""

This is the solution that I came up with trying to solve this problem for myself in order to systematically produce \n’s as separators. It writes using a list of strings where each string is one line of the file, however it seems that it may work for you as well. (Python 3.+)

#Takes a list of strings and prints it to a file.
def writeFile(file, strList):
    line = 0
    lines = []
    while line < len(strList):
        lines.append(cheekyNew(line) + strList[line])
        line += 1
    file = open(file, "w")
    file.writelines(lines)
    file.close()

#Returns "\n" if the int entered isn't zero, otherwise "".
def cheekyNew(line):
    if line != 0:
        return "\n"
    return ""

使用Python将列表写入文件

问题:使用Python将列表写入文件

因为writelines()不插入换行符,这是将列表写入文件的最干净的方法吗?

file.writelines(["%s\n" % item  for item in list])

似乎会有一种标准的方法…

Is this the cleanest way to write a list to a file, since writelines() doesn’t insert newline characters?

file.writelines(["%s\n" % item  for item in list])

It seems like there would be a standard way…


回答 0

您可以使用循环:

with open('your_file.txt', 'w') as f:
    for item in my_list:
        f.write("%s\n" % item)

在Python 2中,您也可以使用

with open('your_file.txt', 'w') as f:
    for item in my_list:
        print >> f, item

如果您热衷于单个函数调用,请至少移除方括号[],以使要打印的字符串一次生成一个(一个genexp而不是一个listcomp)-没有理由占用所有需要的内存具体化整个字符串列表。

You can use a loop:

with open('your_file.txt', 'w') as f:
    for item in my_list:
        f.write("%s\n" % item)

In Python 2, you can also use

with open('your_file.txt', 'w') as f:
    for item in my_list:
        print >> f, item

If you’re keen on a single function call, at least remove the square brackets [], so that the strings to be printed get made one at a time (a genexp rather than a listcomp) — no reason to take up all the memory required to materialize the whole list of strings.


回答 1

您将如何处理该文件?该文件是否存在于人类或具有明确互操作性要求的其他程序中?

如果您只是尝试将列表序列化到磁盘以供同一python应用程序稍后使用,则应该对列表进行腌制

import pickle

with open('outfile', 'wb') as fp:
    pickle.dump(itemlist, fp)

读回:

with open ('outfile', 'rb') as fp:
    itemlist = pickle.load(fp)

What are you going to do with the file? Does this file exist for humans, or other programs with clear interoperability requirements?

If you are just trying to serialize a list to disk for later use by the same python app, you should be pickleing the list.

import pickle

with open('outfile', 'wb') as fp:
    pickle.dump(itemlist, fp)

To read it back:

with open ('outfile', 'rb') as fp:
    itemlist = pickle.load(fp)

回答 2

比较简单的方法是:

with open("outfile", "w") as outfile:
    outfile.write("\n".join(itemlist))

您可以使用生成器表达式来确保项目列表中的所有项目都是字符串:

with open("outfile", "w") as outfile:
    outfile.write("\n".join(str(item) for item in itemlist))

请记住,所有itemlist列表都必须在内存中,因此,请注意内存消耗。

The simpler way is:

with open("outfile", "w") as outfile:
    outfile.write("\n".join(itemlist))

You could ensure that all items in item list are strings using a generator expression:

with open("outfile", "w") as outfile:
    outfile.write("\n".join(str(item) for item in itemlist))

Remember that all itemlist list need to be in memory, so, take care about the memory consumption.


回答 3

使用Python 3Python 2.6+语法:

with open(filepath, 'w') as file_handler:
    for item in the_list:
        file_handler.write("{}\n".format(item))

这是与平台无关的。它还以换行符结束最后一行,这是UNIX的最佳实践

从Python 3.6开始,"{}\n".format(item)可以用f字符串替换:f"{item}\n"

Using Python 3 and Python 2.6+ syntax:

with open(filepath, 'w') as file_handler:
    for item in the_list:
        file_handler.write("{}\n".format(item))

This is platform-independent. It also terminates the final line with a newline character, which is a UNIX best practice.

Starting with Python 3.6, "{}\n".format(item) can be replaced with an f-string: f"{item}\n".


回答 4

还有另一种方式。使用simplejson(在python 2.6中包含为json)序列化为json

>>> import simplejson
>>> f = open('output.txt', 'w')
>>> simplejson.dump([1,2,3,4], f)
>>> f.close()

如果您检查output.txt:

[1、2、3、4]

这很有用,因为语法是pythonic的,它是人类可读的,并且可以由其他语言的其他程序读取。

Yet another way. Serialize to json using simplejson (included as json in python 2.6):

>>> import simplejson
>>> f = open('output.txt', 'w')
>>> simplejson.dump([1,2,3,4], f)
>>> f.close()

If you examine output.txt:

[1, 2, 3, 4]

This is useful because the syntax is pythonic, it’s human readable, and it can be read by other programs in other languages.


回答 5

我认为探索使用genexp的好处会很有趣,所以这是我的看法。

问题中的示例使用方括号创建临时列表,因此等效于:

file.writelines( list( "%s\n" % item for item in list ) )

它不必要地构造了将要写出的所有行的临时列表,这可能会消耗大量内存,具体取决于列表的大小以及输出的详细str(item)程度。

放下方括号(相当于删除list()上面的包装调用)将改为将临时生成器传递给file.writelines()

file.writelines( "%s\n" % item for item in list )

该生成器将item按需创建换行终止的对象表示形式(即,当对象被写出时)。这样做有几个方面的好处:

  • 内存开销很小,即使列表很大
  • 如果str(item)速度较慢,则在处理每个项目时文件中都有可见的进度

这样可以避免出现内存问题,例如:

In [1]: import os

In [2]: f = file(os.devnull, "w")

In [3]: %timeit f.writelines( "%s\n" % item for item in xrange(2**20) )
1 loops, best of 3: 385 ms per loop

In [4]: %timeit f.writelines( ["%s\n" % item for item in xrange(2**20)] )
ERROR: Internal Python error in the inspect module.
Below is the traceback from this internal error.

Traceback (most recent call last):
...
MemoryError

(通过,我通过将Python的最大虚拟内存限制为〜100MB触发了此错误ulimit -v 102400)。

一方面,此方法实际上并没有比原始方法快:

In [4]: %timeit f.writelines( "%s\n" % item for item in xrange(2**20) )
1 loops, best of 3: 370 ms per loop

In [5]: %timeit f.writelines( ["%s\n" % item for item in xrange(2**20)] )
1 loops, best of 3: 360 ms per loop

(Linux上的Python 2.6.2)

I thought it would be interesting to explore the benefits of using a genexp, so here’s my take.

The example in the question uses square brackets to create a temporary list, and so is equivalent to:

file.writelines( list( "%s\n" % item for item in list ) )

Which needlessly constructs a temporary list of all the lines that will be written out, this may consume significant amounts of memory depending on the size of your list and how verbose the output of str(item) is.

Drop the square brackets (equivalent to removing the wrapping list() call above) will instead pass a temporary generator to file.writelines():

file.writelines( "%s\n" % item for item in list )

This generator will create newline-terminated representation of your item objects on-demand (i.e. as they are written out). This is nice for a couple of reasons:

  • Memory overheads are small, even for very large lists
  • If str(item) is slow there’s visible progress in the file as each item is processed

This avoids memory issues, such as:

In [1]: import os

In [2]: f = file(os.devnull, "w")

In [3]: %timeit f.writelines( "%s\n" % item for item in xrange(2**20) )
1 loops, best of 3: 385 ms per loop

In [4]: %timeit f.writelines( ["%s\n" % item for item in xrange(2**20)] )
ERROR: Internal Python error in the inspect module.
Below is the traceback from this internal error.

Traceback (most recent call last):
...
MemoryError

(I triggered this error by limiting Python’s max. virtual memory to ~100MB with ulimit -v 102400).

Putting memory usage to one side, this method isn’t actually any faster than the original:

In [4]: %timeit f.writelines( "%s\n" % item for item in xrange(2**20) )
1 loops, best of 3: 370 ms per loop

In [5]: %timeit f.writelines( ["%s\n" % item for item in xrange(2**20)] )
1 loops, best of 3: 360 ms per loop

(Python 2.6.2 on Linux)


回答 6

因为我很懒…

import json
a = [1,2,3]
with open('test.txt', 'w') as f:
    f.write(json.dumps(a))

#Now read the file back into a Python list object
with open('test.txt', 'r') as f:
    a = json.loads(f.read())

Because i’m lazy….

import json
a = [1,2,3]
with open('test.txt', 'w') as f:
    f.write(json.dumps(a))

#Now read the file back into a Python list object
with open('test.txt', 'r') as f:
    a = json.loads(f.read())

回答 7

将列表序列化为带有逗号分隔值的文本文件

mylist = dir()
with open('filename.txt','w') as f:
    f.write( ','.join( mylist ) )

Serialize list into text file with comma sepparated value

mylist = dir()
with open('filename.txt','w') as f:
    f.write( ','.join( mylist ) )

回答 8

一般来说

以下是writelines()方法的语法

fileObject.writelines( sequence )

#!/usr/bin/python

# Open a file
fo = open("foo.txt", "rw+")
seq = ["This is 6th line\n", "This is 7th line"]

# Write sequence of lines at the end of the file.
line = fo.writelines( seq )

# Close opend file
fo.close()

参考

http://www.tutorialspoint.com/python/file_writelines.htm

In General

Following is the syntax for writelines() method

fileObject.writelines( sequence )

Example

#!/usr/bin/python

# Open a file
fo = open("foo.txt", "rw+")
seq = ["This is 6th line\n", "This is 7th line"]

# Write sequence of lines at the end of the file.
line = fo.writelines( seq )

# Close opend file
fo.close()

Reference

http://www.tutorialspoint.com/python/file_writelines.htm


回答 9

file.write('\n'.join(list))
file.write('\n'.join(list))

回答 10

with open ("test.txt","w")as fp:
   for line in list12:
       fp.write(line+"\n")
with open ("test.txt","w")as fp:
   for line in list12:
       fp.write(line+"\n")

回答 11

如果您使用的是python3,则还可以使用print函数,如下所示。

f = open("myfile.txt","wb")
print(mylist, file=f)

You can also use the print function if you’re on python3 as follows.

f = open("myfile.txt","wb")
print(mylist, file=f)

回答 12

你为什么不尝试

file.write(str(list))

Why don’t you try

file.write(str(list))

回答 13

此逻辑将首先将list中的项目转换为string(str)。有时列表中包含一个元组,例如

alist = [(i12,tiger), 
(113,lion)]

此逻辑将在新行中写入文件每个元组。我们稍后可以eval在读取文件时加载每个元组时使用:

outfile = open('outfile.txt', 'w') # open a file in write mode
for item in list_to_persistence:    # iterate over the list items
   outfile.write(str(item) + '\n') # write to the file
outfile.close()   # close the file 

This logic will first convert the items in list to string(str). Sometimes the list contains a tuple like

alist = [(i12,tiger), 
(113,lion)]

This logic will write to file each tuple in a new line. We can later use eval while loading each tuple when reading the file:

outfile = open('outfile.txt', 'w') # open a file in write mode
for item in list_to_persistence:    # iterate over the list items
   outfile.write(str(item) + '\n') # write to the file
outfile.close()   # close the file 

回答 14

迭代和添加换行符的另一种方法:

for item in items:
    filewriter.write(f"{item}" + "\n")

Another way of iterating and adding newline:

for item in items:
    filewriter.write(f"{item}" + "\n")

回答 15

在python> 3中,您可以将print*用于参数解包:

with open("fout.txt", "w") as fout:
    print(*my_list, sep="\n", file=fout)

In python>3 you can use print and * for argument unpacking:

with open("fout.txt", "w") as fout:
    print(*my_list, sep="\n", file=fout)

回答 16

Python3中,您可以使用此循环

with open('your_file.txt', 'w') as f:
    for item in list:
        f.print("", item)

In Python3 You Can use this loop

with open('your_file.txt', 'w') as f:
    for item in list:
        f.print("", item)

回答 17

让avg作为列表,然后:

In [29]: a = n.array((avg))
In [31]: a.tofile('avgpoints.dat',sep='\n',dtype = '%f')

您可以根据需要使用%e%s

Let avg be the list, then:

In [29]: a = n.array((avg))
In [31]: a.tofile('avgpoints.dat',sep='\n',dtype = '%f')

You can use %e or %s depending on your requirement.


回答 18

poem = '''\
Programming is fun
When the work is done
if you wanna make your work also fun:
use Python!
'''
f = open('poem.txt', 'w') # open for 'w'riting
f.write(poem) # write text to file
f.close() # close the file

工作原理:首先,使用内置的打开功能打开文件,并指定文件名称和我们要打开文件的方式。该模式可以是读取模式(’r’),写入模式(’w’)或追加模式(’a’)。我们还可以指定是以文本模式(’t’)还是二进制模式(’b’)阅读,书写或追加内容。实际上,还有更多可用的模式,help(open)将为您提供有关它们的更多详细信息。默认情况下,open()将文件视为“ t”扩展文件,并以“ r’ead”模式将其打开。在我们的示例中,我们首先以写文本模式打开文件,然后使用文件对象的write方法写入文件,然后最终关闭文件。

上面的示例来自Swaroop C H. swaroopch.com 的书“ A Byte of Python”。

poem = '''\
Programming is fun
When the work is done
if you wanna make your work also fun:
use Python!
'''
f = open('poem.txt', 'w') # open for 'w'riting
f.write(poem) # write text to file
f.close() # close the file

How It Works: First, open a file by using the built-in open function and specifying the name of the file and the mode in which we want to open the file. The mode can be a read mode (’r’), write mode (’w’) or append mode (’a’). We can also specify whether we are reading, writing, or appending in text mode (’t’) or binary mode (’b’). There are actually many more modes available and help(open) will give you more details about them. By default, open() considers the file to be a ’t’ext file and opens it in ’r’ead mode. In our example, we first open the file in write text mode and use the write method of the file object to write to the file and then we finally close the file.

The above example is from the book “A Byte of Python” by Swaroop C H. swaroopch.com


如何在没有换行符或空格的情况下进行打印?

问题:如何在没有换行符或空格的情况下进行打印?

我想在里面做 。我想在这个例子中做什么

在C中:

#include <stdio.h>

int main() {
    int i;
    for (i=0; i<10; i++) printf(".");
    return 0;
}

输出:

..........

在Python中:

>>> for i in range(10): print('.')
.
.
.
.
.
.
.
.
.
.
>>> print('.', '.', '.', '.', '.', '.', '.', '.', '.', '.')
. . . . . . . . . .

在Python中print会添加\n或空格,如何避免呢?现在,这只是一个例子,不要告诉我我可以先构建一个字符串然后再打印它。我想知道如何将字符串“附加”到stdout

I’d like to do it in . What I’d like to do in this example in :

In C:

#include <stdio.h>

int main() {
    int i;
    for (i=0; i<10; i++) printf(".");
    return 0;
}

Output:

..........

In Python:

>>> for i in range(10): print('.')
.
.
.
.
.
.
.
.
.
.
>>> print('.', '.', '.', '.', '.', '.', '.', '.', '.', '.')
. . . . . . . . . .

In Python print will add a \n or space, how can I avoid that? Now, it’s just an example, don’t tell me I can first build a string then print it. I’d like to know how to “append” strings to stdout.


回答 0

在Python 3中,您可以使用函数的sep=end=参数print

不在字符串末尾添加换行符:

print('.', end='')

不在要打印的所有函数参数之间添加空格:

print('a', 'b', 'c', sep='')

您可以将任何字符串传递给任何一个参数,并且可以同时使用两个参数。

如果您在缓冲方面遇到麻烦,可以通过添加flush=True关键字参数来刷新输出:

print('.', end='', flush=True)

Python 2.6和2.7

在Python 2.6中,您可以print使用__future__模块从Python 3 导入函数:

from __future__ import print_function

允许您使用上面的Python 3解决方案。

但是,请注意,在从Python 2中导入flushprint函数的版本中,关键字不可用__future__;它仅适用于Python 3,更具体地说是3.3及更高版本。在早期版本中,您仍然需要通过调用进行手动刷新sys.stdout.flush()。您还必须在执行此导入操作的文件中重写所有其他打印语句。

或者你可以使用 sys.stdout.write()

import sys
sys.stdout.write('.')

您可能还需要调用

sys.stdout.flush()

确保stdout立即冲洗。

In Python 3, you can use the sep= and end= parameters of the print function:

To not add a newline to the end of the string:

print('.', end='')

To not add a space between all the function arguments you want to print:

print('a', 'b', 'c', sep='')

You can pass any string to either parameter, and you can use both parameters at the same time.

If you are having trouble with buffering, you can flush the output by adding flush=True keyword argument:

print('.', end='', flush=True)

Python 2.6 and 2.7

From Python 2.6 you can either import the print function from Python 3 using the __future__ module:

from __future__ import print_function

which allows you to use the Python 3 solution above.

However, note that the flush keyword is not available in the version of the print function imported from __future__ in Python 2; it only works in Python 3, more specifically 3.3 and later. In earlier versions you’ll still need to flush manually with a call to sys.stdout.flush(). You’ll also have to rewrite all other print statements in the file where you do this import.

Or you can use sys.stdout.write()

import sys
sys.stdout.write('.')

You may also need to call

sys.stdout.flush()

to ensure stdout is flushed immediately.


回答 1

它应该像Guido Van Rossum在此链接中描述的那样简单:

回复:没有AC / R的情况下如何打印?

http://legacy.python.org/search/hypermail/python-1992/0115.html

是否可以打印某些内容但不自动附加回车符?

是的,在要打印的最后一个参数之后附加一个逗号。例如,此循环在用空格分隔的一行上打印数字0..9。注意添加最后换行符的无参数“ print”:

>>> for i in range(10):
...     print i,
... else:
...     print
...
0 1 2 3 4 5 6 7 8 9
>>> 

It should be as simple as described at this link by Guido Van Rossum:

Re: How does one print without a c/r ?

http://legacy.python.org/search/hypermail/python-1992/0115.html

Is it possible to print something but not automatically have a carriage return appended to it ?

Yes, append a comma after the last argument to print. For instance, this loop prints the numbers 0..9 on a line separated by spaces. Note the parameterless “print” that adds the final newline:

>>> for i in range(10):
...     print i,
... else:
...     print
...
0 1 2 3 4 5 6 7 8 9
>>> 

回答 2

注意:这个问题的标题曾经是“如何在python中使用printf?”之类的东西。

由于人们可能会来这里根据标题进行查找,因此Python还支持printf样式的替换:

>>> strings = [ "one", "two", "three" ]
>>>
>>> for i in xrange(3):
...     print "Item %d: %s" % (i, strings[i])
...
Item 0: one
Item 1: two
Item 2: three

而且,您可以方便地将字符串值相乘:

>>> print "." * 10
..........

Note: The title of this question used to be something like “How to printf in python?”

Since people may come here looking for it based on the title, Python also supports printf-style substitution:

>>> strings = [ "one", "two", "three" ]
>>>
>>> for i in xrange(3):
...     print "Item %d: %s" % (i, strings[i])
...
Item 0: one
Item 1: two
Item 2: three

And, you can handily multiply string values:

>>> print "." * 10
..........

回答 3

对python2.6 +使用python3样式的打印功能 (还将破坏同一文件中任何现有的关键字打印语句。)

# for python2 to use the print() function, removing the print keyword
from __future__ import print_function
for x in xrange(10):
    print('.', end='')

要不破坏您的所有python2打印关键字,请创建一个单独的printf.py文件

# printf.py

from __future__ import print_function

def printf(str, *args):
    print(str % args, end='')

然后,在您的文件中使用它

from printf import printf
for x in xrange(10):
    printf('.')
print 'done'
#..........done

更多示例展示printf风格

printf('hello %s', 'world')
printf('%i %f', 10, 3.14)
#hello world10 3.140000

Use the python3-style print function for python2.6+ (will also break any existing keyworded print statements in the same file.)

# for python2 to use the print() function, removing the print keyword
from __future__ import print_function
for x in xrange(10):
    print('.', end='')

To not ruin all your python2 print keywords, create a separate printf.py file

# printf.py

from __future__ import print_function

def printf(str, *args):
    print(str % args, end='')

Then, use it in your file

from printf import printf
for x in xrange(10):
    printf('.')
print 'done'
#..........done

More examples showing printf style

printf('hello %s', 'world')
printf('%i %f', 10, 3.14)
#hello world10 3.140000

回答 4

如何在同一行上打印:

import sys
for i in xrange(0,10):
   sys.stdout.write(".")
   sys.stdout.flush()

How to print on the same line:

import sys
for i in xrange(0,10):
   sys.stdout.write(".")
   sys.stdout.flush()

回答 5

新功能(自Python 3.x起)print具有一个可选end参数,可用于修改结尾字符:

print("HELLO", end="")
print("HELLO")

输出:

你好你好

还有sep分隔符:

print("HELLO", "HELLO", "HELLO", sep="")

输出:

你好你好你好

如果您想在Python 2.x中使用它,只需在文件开头添加它:

from __future__ import print_function

The new (as of Python 3.x) print function has an optional end parameter that lets you modify the ending character:

print("HELLO", end="")
print("HELLO")

Output:

HELLOHELLO

There’s also sep for separator:

print("HELLO", "HELLO", "HELLO", sep="")

Output:

HELLOHELLOHELLO

If you wanted to use this in Python 2.x just add this at the start of your file:

from __future__ import print_function


回答 6

使用functools.partial创建一个名为printf的新函数

>>> import functools

>>> printf = functools.partial(print, end="")

>>> printf("Hello world\n")
Hello world

使用默认参数包装函数的简单方法。

Using functools.partial to create a new function called printf

>>> import functools

>>> printf = functools.partial(print, end="")

>>> printf("Hello world\n")
Hello world

Easy way to wrap a function with default parameters.


回答 7

您只需,print函数的末尾添加,这样它就不会在新行上打印。

You can just add , in the end of print function so it won’t print on new line.


回答 8

在Python 3+中,print是一个函数。您打电话的时候

print('hello world')

Python将其转换为

print('hello world', end='\n')

您可以更改end为所需的任何内容。

print('hello world', end='')
print('hello world', end=' ')

In Python 3+, print is a function. When you call

print('hello world')

Python translates it to

print('hello world', end='\n')

You can change end to whatever you want.

print('hello world', end='')
print('hello world', end=' ')

回答 9

python 2.6+

from __future__ import print_function # needs to be first statement in file
print('.', end='')

的Python 3

print('.', end='')

python <= 2.5

import sys
sys.stdout.write('.')

如果每次打印后多余的空间都可以,在python 2中

print '.',

在python 2中产生误导避免

print('.'), # avoid this if you want to remain sane
# this makes it look like print is a function but it is not
# this is the `,` creating a tuple and the parentheses enclose an expression
# to see the problem, try:
print('.', 'x'), # this will print `('.', 'x') `

python 2.6+:

from __future__ import print_function # needs to be first statement in file
print('.', end='')

python 3:

print('.', end='')

python <= 2.5:

import sys
sys.stdout.write('.')

if extra space is OK after each print, in python 2

print '.',

misleading in python 2 – avoid:

print('.'), # avoid this if you want to remain sane
# this makes it look like print is a function but it is not
# this is the `,` creating a tuple and the parentheses enclose an expression
# to see the problem, try:
print('.', 'x'), # this will print `('.', 'x') `

回答 10

你可以试试:

import sys
import time
# Keeps the initial message in buffer.
sys.stdout.write("\rfoobar bar black sheep")
sys.stdout.flush()
# Wait 2 seconds
time.sleep(2)
# Replace the message with a new one.
sys.stdout.write("\r"+'hahahahaaa             ')
sys.stdout.flush()
# Finalize the new message by printing a return carriage.
sys.stdout.write('\n')

You can try:

import sys
import time
# Keeps the initial message in buffer.
sys.stdout.write("\rfoobar bar black sheep")
sys.stdout.flush()
# Wait 2 seconds
time.sleep(2)
# Replace the message with a new one.
sys.stdout.write("\r"+'hahahahaaa             ')
sys.stdout.flush()
# Finalize the new message by printing a return carriage.
sys.stdout.write('\n')

回答 11

您可以在python3中执行以下操作:

#!usr/bin/python

i = 0
while i<10 :
    print('.',end='')
    i = i+1

并用python filename.py或执行python3 filename.py

You can do the same in python3 as follows :

#!usr/bin/python

i = 0
while i<10 :
    print('.',end='')
    i = i+1

and execute it with python filename.py or python3 filename.py


回答 12

我最近有同样的问题..

我通过做解决了:

import sys, os

# reopen stdout with "newline=None".
# in this mode,
# input:  accepts any newline character, outputs as '\n'
# output: '\n' converts to os.linesep

sys.stdout = os.fdopen(sys.stdout.fileno(), "w", newline=None)

for i in range(1,10):
        print(i)

这在Unix和Windows上都可以使用…尚未在macosx上对其进行测试…

hth

i recently had the same problem..

i solved it by doing:

import sys, os

# reopen stdout with "newline=None".
# in this mode,
# input:  accepts any newline character, outputs as '\n'
# output: '\n' converts to os.linesep

sys.stdout = os.fdopen(sys.stdout.fileno(), "w", newline=None)

for i in range(1,10):
        print(i)

this works on both unix and windows … have not tested it on macosx …

hth


回答 13

@lenooh满足了我的查询。我在搜索“ python抑制换行符”时发现了这篇文章。我在Raspberry Pi上使用IDLE3开发用于PuTTY的Python 3.2。我想在PuTTY命令行上创建一个进度条。我不希望页面滚动离开。我想要一条水平线来再次确保用户不会害怕该程序没有停顿下来,也没有在快乐的无限循环中被送去吃午饭-恳求“离开我,我做得很好,但这可能需要一些时间。” 交互式消息-类似于文本中的进度条。

print('Skimming for', search_string, '\b! .001', end='')初始化通过准备下一屏幕写,这将打印3退格作为⌫⌫⌫调刀混合法,然后一个周期,拭去“001”和延伸期间的行中的消息。之后search_string鹦鹉用户输入,\b!修剪我的惊叹号search_string文字背在其上的空间print(),否则的力量,正确放置标点符号。接下来是空格和我正在模拟的“进度条”的第一个“点”。然后,该消息也不必要地以页码填充(格式为长度为3的长度,前导零),以引起用户的注意,正在处理进度,这也将反映出我们稍后将构建的周期数对。

import sys

page=1
search_string=input('Search for?',)
print('Skimming for', search_string, '\b! .001', end='')
sys.stdout.flush() # the print function with an end='' won't print unless forced
while page:
    # some stuff…
    # search, scrub, and build bulk output list[], count items,
    # set done flag True
    page=page+1 #done flag set in 'some_stuff'
    sys.stdout.write('\b\b\b.'+format(page, '03')) #<-- here's the progress bar meat
    sys.stdout.flush()
    if done: #( flag alternative to break, exit or quit)
        print('\nSorting', item_count, 'items')
        page=0 # exits the 'while page' loop
list.sort()
for item_count in range(0, items)
    print(list[item_count])
#print footers here
 if not (len(list)==items):
    print('#error_handler')

进度栏处在sys.stdout.write('\b\b\b.'+format(page, '03'))排队状态。首先,要擦除到左侧,它会将光标备份到三个数字字符上,并以’\ b \ b \ b’作为⌫⌫⌫摩擦,并放下新的句点以增加进度条的长度。然后,它写入到目前为止的页面的三位数。由于sys.stdout.write()等待完整的缓冲区或输出通道关闭,因此sys.stdout.flush()强制立即写入。sys.stdout.flush()内置到末尾,print()而则绕过print(txt, end='' )。然后,代码循环执行其繁琐的时间密集型操作,同时不再打印任何内容,直到返回此处擦除三位数字,添加一个句点并再次写入三位数字(递增)。

擦拭和重写的三个数字是没有必要的手段-它只是一个蓬勃发展,其例证了sys.stdout.write()对比print()。您只需将周期条每次打印更长的时间,就可以很容易地给句号加注,而忘记三个花哨的反斜杠-b⌫退格键(当然也不会写入格式化的页数),而无需使用空格或换行符,而只需使用sys.stdout.write('.'); sys.stdout.flush()对。

请注意,Raspberry Pi IDLE3 Python外壳程序不将Backspace用作⌫rubout,而是打印一个空格,而是创建一个明显的分数列表。

-(o = 8> wiz

@lenooh satisfied my query. I discovered this article while searching for ‘python suppress newline’. I’m using IDLE3 on Raspberry Pi to develop Python 3.2 for PuTTY. I wanted to create a progress bar on the PuTTY command line. I didn’t want the page scrolling away. I wanted a horizontal line to re-assure the user from freaking out that the program hasn’t cruncxed to a halt nor been sent to lunch on a merry infinite loop – as a plea to ‘leave me be, I’m doing fine, but this may take some time.’ interactive message – like a progress bar in text.

The print('Skimming for', search_string, '\b! .001', end='') initializes the message by preparing for the next screen-write, which will print three backspaces as ⌫⌫⌫ rubout and then a period, wiping off ‘001’ and extending the line of periods. After search_string parrots user input, the \b! trims the exclamation point of my search_string text to back over the space which print() otherwise forces, properly placing the punctuation. That’s followed by a space and the first ‘dot’ of the ‘progress bar’ which I’m simulating. Unnecessarily, the message is also then primed with the page number (formatted to a length of three with leading zeros) to take notice from the user that progress is being processed and which will also reflect the count of periods we will later build out to the right.

import sys

page=1
search_string=input('Search for?',)
print('Skimming for', search_string, '\b! .001', end='')
sys.stdout.flush() # the print function with an end='' won't print unless forced
while page:
    # some stuff…
    # search, scrub, and build bulk output list[], count items,
    # set done flag True
    page=page+1 #done flag set in 'some_stuff'
    sys.stdout.write('\b\b\b.'+format(page, '03')) #<-- here's the progress bar meat
    sys.stdout.flush()
    if done: #( flag alternative to break, exit or quit)
        print('\nSorting', item_count, 'items')
        page=0 # exits the 'while page' loop
list.sort()
for item_count in range(0, items)
    print(list[item_count])
#print footers here
 if not (len(list)==items):
    print('#error_handler')

The progress bar meat is in the sys.stdout.write('\b\b\b.'+format(page, '03')) line. First, to erase to the left, it backs up the cursor over the three numeric characters with the ‘\b\b\b’ as ⌫⌫⌫ rubout and drops a new period to add to the progress bar length. Then it writes three digits of the page it has progressed to so far. Because sys.stdout.write() waits for a full buffer or the output channel to close, the sys.stdout.flush() forces the immediate write. sys.stdout.flush() is built into the end of print() which is bypassed with print(txt, end='' ). Then the code loops through its mundane time intensive operations while it prints nothing more until it returns here to wipe three digits back, add a period and write three digits again, incremented.

The three digits wiped and rewritten is by no means necessary – it’s just a flourish which exemplifies sys.stdout.write() versus print(). You could just as easily prime with a period and forget the three fancy backslash-b ⌫ backspaces (of course not writing formatted page counts as well) by just printing the period bar longer by one each time through – without spaces or newlines using just the sys.stdout.write('.'); sys.stdout.flush() pair.

Please note that the Raspberry Pi IDLE3 Python shell does not honor the backspace as ⌫ rubout but instead prints a space, creating an apparent list of fractions instead.

—(o=8> wiz


回答 14

您会注意到上述所有答案都是正确的。但是我想做一个捷径,总是总是在最后写入“ end =”参数。

你可以定义一个像

def Print(*args,sep='',end='',file=None,flush=False):
    print(*args,sep=sep,end=end,file=file,flush=flush)

它将接受所有数量的参数。即使它将接受所有其他参数,如file,flush等,并使用相同的名称。

You will notice that all the above answers are correct. But I wanted to make a shortcut to always writing the ” end=” ” parameter in the end.

You could define a function like

def Print(*args,sep='',end='',file=None,flush=False):
    print(*args,sep=sep,end=end,file=file,flush=flush)

It would accept all the number of parameters. Even it will accept all the other parameters like file, flush ,etc and with the same name.


回答 15

这些答案中的许多似乎有些复杂。在Python 3.x中,您只需执行以下操作:

print(<expr>, <expr>, ..., <expr>, end=" ")

end的默认值是"\n"。我们只是将其更改为空格,或者您也可以使用end=""(没有空格)执行printf通常的操作。

Many of these answers seem a little complicated. In Python 3.x you simply do this:

print(<expr>, <expr>, ..., <expr>, end=" ")

The default value of end is "\n". We are simply changing it to a space or you can also use end="" (no space) to do what printf normally does.


回答 16

您想在for循环中打印一些内容;但是您不希望它每次都在新行中打印..例如:

 for i in range (0,5):
   print "hi"

 OUTPUT:
    hi
    hi
    hi
    hi
    hi

但是您希望它像这样打印:嗨,嗨,嗨,嗨,嗨?只需在打印“ hi”后添加一个逗号

例:

for i in range (0,5): print "hi", OUTPUT: hi hi hi hi hi

you want to print something in for loop right;but you don’t want it print in new line every time.. for example:

 for i in range (0,5):
   print "hi"

 OUTPUT:
    hi
    hi
    hi
    hi
    hi

but you want it to print like this: hi hi hi hi hi hi right???? just add a comma after print “hi”

Example:

for i in range (0,5): print "hi", OUTPUT: hi hi hi hi hi


回答 17

或具有以下功能:

def Print(s):
   return sys.stdout.write(str(s))

那么现在:

for i in range(10): # or `xrange` for python 2 version
   Print(i)

输出:

0123456789

Or have a function like:

def Print(s):
   return sys.stdout.write(str(s))

Then now:

for i in range(10): # or `xrange` for python 2 version
   Print(i)

Outputs:

0123456789

回答 18

for i in xrange(0,10): print '\b.',

这在2.7.8和2.5.2(分别为Canopy和OSX终端)中都有效-不需要模块导入或时间旅行。

for i in xrange(0,10): print '\b.',

This worked in both 2.7.8 & 2.5.2 (Canopy and OSX terminal, respectively) — no module imports or time travel required.


回答 19

一般有两种方法可以做到这一点:

在Python 3.x中不使用换行符进行打印

在print语句之后不添加任何内容,并使用end='' as 删除’\ n’ :

>>> print('hello')
hello  # appending '\n' automatically
>>> print('world')
world # with previous '\n' world comes down

# solution is:
>>> print('hello', end='');print(' world'); # end with anything like end='-' or end=" " but not '\n'
hello world # it seem correct output

循环中的另一个示例

for i in range(1,10):
    print(i, end='.')

在Python 2.x中不使用换行符进行打印

添加结尾逗号表示打印后忽略\n

>>> print "hello",; print" world"
hello world

循环中的另一个示例

for i in range(1,10):
    print "{} .".format(i),

希望这会帮助你。您可以访问此链接

There are general two ways to do this:

Print without newline in Python 3.x

Append nothing after the print statement and remove ‘\n’ by using end='' as:

>>> print('hello')
hello  # appending '\n' automatically
>>> print('world')
world # with previous '\n' world comes down

# solution is:
>>> print('hello', end='');print(' world'); # end with anything like end='-' or end=" " but not '\n'
hello world # it seem correct output

Another Example in Loop:

for i in range(1,10):
    print(i, end='.')

Print without newline in Python 2.x

Adding a trailing comma says that after print ignore \n.

>>> print "hello",; print" world"
hello world

Another Example in Loop:

for i in range(1,10):
    print "{} .".format(i),

Hope this will help you. You can visit this link .


回答 20

…您不需要导入任何库。只需使用删除字符:

BS=u'\0008' # the unicode for "delete" character
for i in range(10):print(BS+"."),

这将删除换行符和空格(^ _ ^)*

…you do not need to import any library. Just use the delete character:

BS=u'\0008' # the unicode for "delete" character
for i in range(10):print(BS+"."),

this removes the newline and the space (^_^)*


如何删除尾随换行符?

问题:如何删除尾随换行符?

Python与Perl chomp函数等效吗?如果是换行符,它将删除字符串的最后符?

What is the Python equivalent of Perl’s chomp function, which removes the last character of a string if it is a newline?


回答 0

试用该方法rstrip()(请参阅doc Python 2Python 3

>>> 'test string\n'.rstrip()
'test string'

Python的rstrip()方法去除所有的默认类型的尾随空白的,如Perl并与不只是一个换行符chomp

>>> 'test string \n \r\n\n\r \n\n'.rstrip()
'test string'

要只删除换行符:

>>> 'test string \n \r\n\n\r \n\n'.rstrip('\n')
'test string \n \r\n\n\r '

还有一些方法lstrip()strip()

>>> s = "   \n\r\n  \n  abc   def \n\r\n  \n  "
>>> s.strip()
'abc   def'
>>> s.lstrip()
'abc   def \n\r\n  \n  '
>>> s.rstrip()
'   \n\r\n  \n  abc   def'

Try the method rstrip() (see doc Python 2 and Python 3)

>>> 'test string\n'.rstrip()
'test string'

Python’s rstrip() method strips all kinds of trailing whitespace by default, not just one newline as Perl does with chomp.

>>> 'test string \n \r\n\n\r \n\n'.rstrip()
'test string'

To strip only newlines:

>>> 'test string \n \r\n\n\r \n\n'.rstrip('\n')
'test string \n \r\n\n\r '

There are also the methods lstrip() and strip():

>>> s = "   \n\r\n  \n  abc   def \n\r\n  \n  "
>>> s.strip()
'abc   def'
>>> s.lstrip()
'abc   def \n\r\n  \n  '
>>> s.rstrip()
'   \n\r\n  \n  abc   def'

回答 1

我想说的是,在不尾随换行符的情况下获取行的“ pythonic”方法是splitlines()。

>>> text = "line 1\nline 2\r\nline 3\nline 4"
>>> text.splitlines()
['line 1', 'line 2', 'line 3', 'line 4']

And I would say the “pythonic” way to get lines without trailing newline characters is splitlines().

>>> text = "line 1\nline 2\r\nline 3\nline 4"
>>> text.splitlines()
['line 1', 'line 2', 'line 3', 'line 4']

回答 2

删除行尾(EOL)字符的规范方法是使用字符串rstrip()方法,删除任何尾随的\ r或\ n。以下是Mac,Windows和Unix EOL字符的示例。

>>> 'Mac EOL\r'.rstrip('\r\n')
'Mac EOL'
>>> 'Windows EOL\r\n'.rstrip('\r\n')
'Windows EOL'
>>> 'Unix EOL\n'.rstrip('\r\n')
'Unix EOL'

使用’\ r \ n’作为rstrip的参数意味着它会去除’\ r’或’\ n’的任何尾随组合。这就是为什么它在以上所有三种情况下都有效的原因。

这种细微差别在极少数情况下很重要。例如,我曾经不得不处理一个包含HL7消息的文本文件。HL7标准要求结尾的’\ r’作为其EOL字符。我在其上使用此消息的Windows计算机附加了自己的’\ r \ n’EOL字符。因此,每行的末尾看起来像’\ r \ r \ n’。使用rstrip(’\ r \ n’)会删除整个’\ r \ r \ n’,这不是我想要的。在那种情况下,我只是切掉了最后两个字符。

请注意,与Perl的chomp函数不同,这将在字符串的末尾去除所有指定的字符,而不仅仅是一个:

>>> "Hello\n\n\n".rstrip("\n")
"Hello"

The canonical way to strip end-of-line (EOL) characters is to use the string rstrip() method removing any trailing \r or \n. Here are examples for Mac, Windows, and Unix EOL characters.

>>> 'Mac EOL\r'.rstrip('\r\n')
'Mac EOL'
>>> 'Windows EOL\r\n'.rstrip('\r\n')
'Windows EOL'
>>> 'Unix EOL\n'.rstrip('\r\n')
'Unix EOL'

Using ‘\r\n’ as the parameter to rstrip means that it will strip out any trailing combination of ‘\r’ or ‘\n’. That’s why it works in all three cases above.

This nuance matters in rare cases. For example, I once had to process a text file which contained an HL7 message. The HL7 standard requires a trailing ‘\r’ as its EOL character. The Windows machine on which I was using this message had appended its own ‘\r\n’ EOL character. Therefore, the end of each line looked like ‘\r\r\n’. Using rstrip(‘\r\n’) would have taken off the entire ‘\r\r\n’ which is not what I wanted. In that case, I simply sliced off the last two characters instead.

Note that unlike Perl’s chomp function, this will strip all specified characters at the end of the string, not just one:

>>> "Hello\n\n\n".rstrip("\n")
"Hello"

回答 3

请注意,rstrip的行为与Perl的chomp()并不完全相同,因为它不会修改字符串。也就是说,在Perl中:

$x="a\n";

chomp $x

导致$x存在"a"

但在Python中:

x="a\n"

x.rstrip()

将意味着价值x依旧 "a\n"。甚至x=x.rstrip()并不总是给出相同的结果,因为它从字符串的末尾去除所有空格,最多不只是一个换行符。

Note that rstrip doesn’t act exactly like Perl’s chomp() because it doesn’t modify the string. That is, in Perl:

$x="a\n";

chomp $x

results in $x being "a".

but in Python:

x="a\n"

x.rstrip()

will mean that the value of x is still "a\n". Even x=x.rstrip() doesn’t always give the same result, as it strips all whitespace from the end of the string, not just one newline at most.


回答 4

我可能会使用这样的东西:

import os
s = s.rstrip(os.linesep)

我认为问题rstrip("\n")在于您可能需要确保行分隔符是可移植的。(有传闻说有些过时的系统要使用"\r\n")。另一个难题是,rstrip它将去除重复的空白。希望os.linesep将包含正确的字符。以上对我有用。

I might use something like this:

import os
s = s.rstrip(os.linesep)

I think the problem with rstrip("\n") is that you’ll probably want to make sure the line separator is portable. (some antiquated systems are rumored to use "\r\n"). The other gotcha is that rstrip will strip out repeated whitespace. Hopefully os.linesep will contain the right characters. the above works for me.


回答 5

您可以使用line = line.rstrip('\n')。这将从字符串末尾除去所有换行符,而不仅仅是一条。

You may use line = line.rstrip('\n'). This will strip all newlines from the end of the string, not just one.


回答 6

s = s.rstrip()

将删除字符串末尾的所有换行符s。需要分配是因为rstrip返回一个新字符串而不是修改原始字符串。

s = s.rstrip()

will remove all newlines at the end of the string s. The assignment is needed because rstrip returns a new string instead of modifying the original string.


回答 7

这将为“ \ n”行终止符精确复制perl的champ(数组的负行为):

def chomp(x):
    if x.endswith("\r\n"): return x[:-2]
    if x.endswith("\n") or x.endswith("\r"): return x[:-1]
    return x

(注意:它不会修改字符串“就地”;它不会去除多余的尾随空格;需要考虑\ r \ n)

This would replicate exactly perl’s chomp (minus behavior on arrays) for “\n” line terminator:

def chomp(x):
    if x.endswith("\r\n"): return x[:-2]
    if x.endswith("\n") or x.endswith("\r"): return x[:-1]
    return x

(Note: it does not modify string ‘in place’; it does not strip extra trailing whitespace; takes \r\n in account)


回答 8

"line 1\nline 2\r\n...".replace('\n', '').replace('\r', '')
>>> 'line 1line 2...'

否则您总是可以通过regexp变得更加怪异:)

玩得开心!

"line 1\nline 2\r\n...".replace('\n', '').replace('\r', '')
>>> 'line 1line 2...'

or you could always get geekier with regexps :)

have fun!


回答 9

您可以使用地带:

line = line.strip()

演示:

>>> "\n\n hello world \n\n".strip()
'hello world'

you can use strip:

line = line.strip()

demo:

>>> "\n\n hello world \n\n".strip()
'hello world'

回答 10

rstrip在很多级别上都没有与chomp相同的功能。阅读http://perldoc.perl.org/functions/chomp.html,发现chomp确实非常复杂。

但是,我的主要观点是chomp最多删除1个行尾,而rstrip会删除尽可能多的行。

在这里,您可以看到rstrip删除了所有换行符:

>>> 'foo\n\n'.rstrip(os.linesep)
'foo'

可以使用re.sub来更接近典型的Perl chomp用法,如下所示:

>>> re.sub(os.linesep + r'\Z','','foo\n\n')
'foo\n'

rstrip doesn’t do the same thing as chomp, on so many levels. Read http://perldoc.perl.org/functions/chomp.html and see that chomp is very complex indeed.

However, my main point is that chomp removes at most 1 line ending, whereas rstrip will remove as many as it can.

Here you can see rstrip removing all the newlines:

>>> 'foo\n\n'.rstrip(os.linesep)
'foo'

A much closer approximation of typical Perl chomp usage can be accomplished with re.sub, like this:

>>> re.sub(os.linesep + r'\Z','','foo\n\n')
'foo\n'

回答 11

注意"foo".rstrip(os.linesep):只会砍断正在执行Python的平台的换行符。想象一下,例如,您正在用Linux整理Windows文件的行,例如:

$ python
Python 2.7.1 (r271:86832, Mar 18 2011, 09:09:48) 
[GCC 4.5.0 20100604 [gcc-4_5-branch revision 160292]] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os, sys
>>> sys.platform
'linux2'
>>> "foo\r\n".rstrip(os.linesep)
'foo\r'
>>>

"foo".rstrip("\r\n")如Mike所说,请改用。

Careful with "foo".rstrip(os.linesep): That will only chomp the newline characters for the platform where your Python is being executed. Imagine you’re chimping the lines of a Windows file under Linux, for instance:

$ python
Python 2.7.1 (r271:86832, Mar 18 2011, 09:09:48) 
[GCC 4.5.0 20100604 [gcc-4_5-branch revision 160292]] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os, sys
>>> sys.platform
'linux2'
>>> "foo\r\n".rstrip(os.linesep)
'foo\r'
>>>

Use "foo".rstrip("\r\n") instead, as Mike says above.


回答 12

Python文档中示例仅使用line.strip()

Perl的chomp函数仅在字符串末尾才删除一个换行序列。

如果process从概念上来说,这是我需要执行的功能,以便对该文件的每一行都有用,这就是我打算在Python 中执行的操作:

import os
sep_pos = -len(os.linesep)
with open("file.txt") as f:
    for line in f:
        if line[sep_pos:] == os.linesep:
            line = line[:sep_pos]
        process(line)

An example in Python’s documentation simply uses line.strip().

Perl’s chomp function removes one linebreak sequence from the end of a string only if it’s actually there.

Here is how I plan to do that in Python, if process is conceptually the function that I need in order to do something useful to each line from this file:

import os
sep_pos = -len(os.linesep)
with open("file.txt") as f:
    for line in f:
        if line[sep_pos:] == os.linesep:
            line = line[:sep_pos]
        process(line)

回答 13

我不使用Python编程,但是在python.org上遇到了一个常见问题解答,主张S.rstrip(“ \ r \ n”)适用于python 2.2或更高版本。

I don’t program in Python, but I came across an FAQ at python.org advocating S.rstrip(“\r\n”) for python 2.2 or later.


回答 14

import re

r_unwanted = re.compile("[\n\t\r]")
r_unwanted.sub("", your_text)
import re

r_unwanted = re.compile("[\n\t\r]")
r_unwanted.sub("", your_text)

回答 15

我发现能够通过迭代器获得短线很方便,这与从文件对象中获得短线的方式相似。您可以使用以下代码进行操作:

def chomped_lines(it):
    return map(operator.methodcaller('rstrip', '\r\n'), it)

用法示例:

with open("file.txt") as infile:
    for line in chomped_lines(infile):
        process(line)

I find it convenient to have be able to get the chomped lines via in iterator, parallel to the way you can get the un-chomped lines from a file object. You can do so with the following code:

def chomped_lines(it):
    return map(operator.methodcaller('rstrip', '\r\n'), it)

Sample usage:

with open("file.txt") as infile:
    for line in chomped_lines(infile):
        process(line)

回答 16

特殊情况的解决方法:

如果换行符是最后符(大多数文件输入都是这种情况),那么对于集合中的任何元素,您都可以按如下所示进行索引:

foobar= foobar[:-1]

切出换行符。

workaround solution for special case:

if the newline character is the last character (as is the case with most file inputs), then for any element in the collection you can index as follows:

foobar= foobar[:-1]

to slice out your newline character.


回答 17

如果您的问题是清理多行str对象(oldstr)中的所有换行符,则可以根据定界符’\ n’将其拆分为一个列表,然后将该列表加入一个新的str(newstr)中。

newstr = "".join(oldstr.split('\n'))

If your question is to clean up all the line breaks in a multiple line str object (oldstr), you can split it into a list according to the delimiter ‘\n’ and then join this list into a new str(newstr).

newstr = "".join(oldstr.split('\n'))


回答 18

它看起来像没有用于Perl的一个完美的模拟格格。尤其是,rstrip无法处理多字符换行符分隔符,例如\r\n。但是,分割线确实如此处指出。按照对另一个问题的回答,您可以结合使用joinsplitlines来删除/替换字符串中的所有换行符s

''.join(s.splitlines())

以下内容仅删除了一条尾随的换行符(我相信像排行一样)。Truekeepends参数作为分割线传递时保留定界符。然后,再次调用splitlines以删除最后一个“行”上的分隔符:

def chomp(s):
    if len(s):
        lines = s.splitlines(True)
        last = lines.pop()
        return ''.join(lines + last.splitlines())
    else:
        return ''

It looks like there is not a perfect analog for perl’s chomp. In particular, rstrip cannot handle multi-character newline delimiters like \r\n. However, splitlines does as pointed out here. Following my answer on a different question, you can combine join and splitlines to remove/replace all newlines from a string s:

''.join(s.splitlines())

The following removes exactly one trailing newline (as chomp would, I believe). Passing True as the keepends argument to splitlines retain the delimiters. Then, splitlines is called again to remove the delimiters on just the last “line”:

def chomp(s):
    if len(s):
        lines = s.splitlines(True)
        last = lines.pop()
        return ''.join(lines + last.splitlines())
    else:
        return ''

回答 19

我正在从先前在其他答案的评论中发布的答案中冒充基于正则表达式的答案。我认为使用re可以解决此问题str.rstrip

>>> import re

如果要删除一个或多个尾随换行符,请执行以下操作:

>>> re.sub(r'[\n\r]+$', '', '\nx\r\n')
'\nx'

如果要在各处删除换行符(不只是尾随):

>>> re.sub(r'[\n\r]+', '', '\nx\r\n')
'x'

如果你想删除只有1-2尾随换行字符(即\r\n\r\n\n\r\r\r\n\n

>>> re.sub(r'[\n\r]{1,2}$', '', '\nx\r\n\r\n')
'\nx\r'
>>> re.sub(r'[\n\r]{1,2}$', '', '\nx\r\n\r')
'\nx\r'
>>> re.sub(r'[\n\r]{1,2}$', '', '\nx\r\n')
'\nx'

我有一种感觉,大多数人真的想在这里,是消除只是一个发生尾随换行符的,无论是\r\n\n仅此而已。

>>> re.sub(r'(?:\r\n|\n)$', '', '\nx\n\n', count=1)
'\nx\n'
>>> re.sub(r'(?:\r\n|\n)$', '', '\nx\r\n\r\n', count=1)
'\nx\r\n'
>>> re.sub(r'(?:\r\n|\n)$', '', '\nx\r\n', count=1)
'\nx'
>>> re.sub(r'(?:\r\n|\n)$', '', '\nx\n', count=1)
'\nx'

?:创建一个非捕获组。)

(顺便说一句,这不是做什么'...'.rstrip('\n', '').rstrip('\r', ''),其他人可能不会在这个线程上绊脚石。 str.rstrip剥离掉尽可能多的尾随字符,因此,像这样的字符串foo\n\n\n会导致的误报,foo而您可能想保留除去尾随单个后的其他换行符。)

I’m bubbling up my regular expression based answer from one I posted earlier in the comments of another answer. I think using re is a clearer more explicit solution to this problem than str.rstrip.

>>> import re

If you want to remove one or more trailing newline chars:

>>> re.sub(r'[\n\r]+$', '', '\nx\r\n')
'\nx'

If you want to remove newline chars everywhere (not just trailing):

>>> re.sub(r'[\n\r]+', '', '\nx\r\n')
'x'

If you want to remove only 1-2 trailing newline chars (i.e., \r, \n, \r\n, \n\r, \r\r, \n\n)

>>> re.sub(r'[\n\r]{1,2}$', '', '\nx\r\n\r\n')
'\nx\r'
>>> re.sub(r'[\n\r]{1,2}$', '', '\nx\r\n\r')
'\nx\r'
>>> re.sub(r'[\n\r]{1,2}$', '', '\nx\r\n')
'\nx'

I have a feeling what most people really want here, is to remove just one occurrence of a trailing newline character, either \r\n or \n and nothing more.

>>> re.sub(r'(?:\r\n|\n)$', '', '\nx\n\n', count=1)
'\nx\n'
>>> re.sub(r'(?:\r\n|\n)$', '', '\nx\r\n\r\n', count=1)
'\nx\r\n'
>>> re.sub(r'(?:\r\n|\n)$', '', '\nx\r\n', count=1)
'\nx'
>>> re.sub(r'(?:\r\n|\n)$', '', '\nx\n', count=1)
'\nx'

(The ?: is to create a non-capturing group.)

(By the way this is not what '...'.rstrip('\n', '').rstrip('\r', '') does which may not be clear to others stumbling upon this thread. str.rstrip strips as many of the trailing characters as possible, so a string like foo\n\n\n would result in a false positive of foo whereas you may have wanted to preserve the other newlines after stripping a single trailing one.)


回答 20

>>> '   spacious   '.rstrip()
'   spacious'
>>> "AABAA".rstrip("A")
  'AAB'
>>> "ABBA".rstrip("AB") # both AB and BA are stripped
   ''
>>> "ABCABBA".rstrip("AB")
   'ABC'
>>> '   spacious   '.rstrip()
'   spacious'
>>> "AABAA".rstrip("A")
  'AAB'
>>> "ABBA".rstrip("AB") # both AB and BA are stripped
   ''
>>> "ABCABBA".rstrip("AB")
   'ABC'

回答 21

只需使用:

line = line.rstrip("\n")

要么

line = line.strip("\n")

您不需要这些复杂的东西

Just use :

line = line.rstrip("\n")

or

line = line.strip("\n")

You don’t need any of this complicated stuff


回答 22

s = '''Hello  World \t\n\r\tHi There'''
# import the module string   
import string
# use the method translate to convert 
s.translate({ord(c): None for c in string.whitespace}
>>'HelloWorldHiThere'

与正则表达式

s = '''  Hello  World 
\t\n\r\tHi '''
print(re.sub(r"\s+", "", s), sep='')  # \s matches all white spaces
>HelloWorldHi

替换\ n,\ t,\ r

s.replace('\n', '').replace('\t','').replace('\r','')
>'  Hello  World Hi '

与正则表达式

s = '''Hello  World \t\n\r\tHi There'''
regex = re.compile(r'[\n\r\t]')
regex.sub("", s)
>'Hello  World Hi There'

与加入

s = '''Hello  World \t\n\r\tHi There'''
' '.join(s.split())
>'Hello  World Hi There'
s = '''Hello  World \t\n\r\tHi There'''
# import the module string   
import string
# use the method translate to convert 
s.translate({ord(c): None for c in string.whitespace}
>>'HelloWorldHiThere'

With regex

s = '''  Hello  World 
\t\n\r\tHi '''
print(re.sub(r"\s+", "", s), sep='')  # \s matches all white spaces
>HelloWorldHi

Replace \n,\t,\r

s.replace('\n', '').replace('\t','').replace('\r','')
>'  Hello  World Hi '

With regex

s = '''Hello  World \t\n\r\tHi There'''
regex = re.compile(r'[\n\r\t]')
regex.sub("", s)
>'Hello  World Hi There'

with Join

s = '''Hello  World \t\n\r\tHi There'''
' '.join(s.split())
>'Hello  World Hi There'

回答 23

有三种类型的行结尾的,我们常遇到的问题:\n\r\r\n。中的一个相当简单的正则表达式re.sub,即r"\r?\n?$",能够将它们全部捕获。

(而且我们要抓住一切,对吗?)

import re

re.sub(r"\r?\n?$", "", the_text, 1)

对于最后一个参数,我们将替换的出现次数限制为一次,从而在某种程度上模仿了chomp。例:

import re

text_1 = "hellothere\n\n\n"
text_2 = "hellothere\n\n\r"
text_3 = "hellothere\n\n\r\n"

a = re.sub(r"\r?\n?$", "", text_1, 1)
b = re.sub(r"\r?\n?$", "", text_2, 1)
c = re.sub(r"\r?\n?$", "", text_3, 1)

…这里a == b == cTrue

There are three types of line endings that we normally encounter: \n, \r and \r\n. A rather simple regular expression in re.sub, namely r"\r?\n?$", is able to catch them all.

(And we gotta catch ’em all, am I right?)

import re

re.sub(r"\r?\n?$", "", the_text, 1)

With the last argument, we limit the number of occurences replaced to one, mimicking chomp to some extent. Example:

import re

text_1 = "hellothere\n\n\n"
text_2 = "hellothere\n\n\r"
text_3 = "hellothere\n\n\r\n"

a = re.sub(r"\r?\n?$", "", text_1, 1)
b = re.sub(r"\r?\n?$", "", text_2, 1)
c = re.sub(r"\r?\n?$", "", text_3, 1)

… where a == b == c is True.


回答 24

如果您担心速度(例如,您有很长的字符串列表)并且知道换行符char的性质,则字符串切片实际上比rstrip快。进行一点测试以说明这一点:

import time

loops = 50000000

def method1(loops=loops):
    test_string = 'num\n'
    t0 = time.time()
    for num in xrange(loops):
        out_sting = test_string[:-1]
    t1 = time.time()
    print('Method 1: ' + str(t1 - t0))

def method2(loops=loops):
    test_string = 'num\n'
    t0 = time.time()
    for num in xrange(loops):
        out_sting = test_string.rstrip()
    t1 = time.time()
    print('Method 2: ' + str(t1 - t0))

method1()
method2()

输出:

Method 1: 3.92700004578
Method 2: 6.73000001907

If you are concerned about speed (say you have a looong list of strings) and you know the nature of the newline char, string slicing is actually faster than rstrip. A little test to illustrate this:

import time

loops = 50000000

def method1(loops=loops):
    test_string = 'num\n'
    t0 = time.time()
    for num in xrange(loops):
        out_sting = test_string[:-1]
    t1 = time.time()
    print('Method 1: ' + str(t1 - t0))

def method2(loops=loops):
    test_string = 'num\n'
    t0 = time.time()
    for num in xrange(loops):
        out_sting = test_string.rstrip()
    t1 = time.time()
    print('Method 2: ' + str(t1 - t0))

method1()
method2()

Output:

Method 1: 3.92700004578
Method 2: 6.73000001907

回答 25


这将同时适用于Windows和Linux(如果您只寻求re解决方案,那么re sub会有点贵)

import re 
if re.search("(\\r|)\\n$", line):
    line = re.sub("(\\r|)\\n$", "", line)


This will work both for windows and linux (bit expensive with re sub if you are looking for only re solution)

import re 
if re.search("(\\r|)\\n$", line):
    line = re.sub("(\\r|)\\n$", "", line)


回答 26

首先分割线,然后通过您喜欢的任何分隔符将它们连接起来:

x = ' '.join(x.splitlines())

应该像魅力一样工作。

First split lines then join them by any separator you like:

x = ' '.join(x.splitlines())

should work like a charm.


回答 27

一网打尽:

line = line.rstrip('\r|\n')

A catch all:

line = line.rstrip('\r|\n')