问题:删除前导和尾随空格?

我很难尝试将.strip与以下代码行结合使用。

谢谢您的帮助。

f.write(re.split("Tech ID:|Name:|Account #:",line)[-1])

I’m having a hard time trying to use .strip with the following line of code.

Thanks for the help.

f.write(re.split("Tech ID:|Name:|Account #:",line)[-1])

回答 0

您可以使用strip()删除尾随和前导空格。

>>> s = '   abd cde   '
>>> s.strip()
'abd cde'

注意:内部空间被保留

You can use the strip() to remove trailing and leading spaces.

>>> s = '   abd cde   '
>>> s.strip()
'abd cde'

Note: the internal spaces are preserved


回答 1

将您的一根衬里扩展为多行。然后变得容易:

f.write(re.split("Tech ID:|Name:|Account #:",line)[-1])

parts = re.split("Tech ID:|Name:|Account #:",line)
wanted_part = parts[-1]
wanted_part_stripped = wanted_part.strip()
f.write(wanted_part_stripped)

Expand your one liner into multiple lines. Then it becomes easy:

f.write(re.split("Tech ID:|Name:|Account #:",line)[-1])

parts = re.split("Tech ID:|Name:|Account #:",line)
wanted_part = parts[-1]
wanted_part_stripped = wanted_part.strip()
f.write(wanted_part_stripped)

回答 2

应该注意的是,该strip()方法将修剪字符串中的任何前导和尾随空白字符(如果没有传入的参数)。如果要修剪空格字符,同时保留其他字符(例如换行符),此答案可能会有所帮助:

sample = '  some string\n'
sample_modified = sample.strip(' ')

print(sample_modified)  # will print 'some string\n'

strip([chars]):您可以将可选字符传递给strip([chars])方法。Python将查找这些字符的出现并相应地修剪给定的字符串。

Should be noted that strip() method would trim any leading and trailing whitespace characters from the string (if there is no passed-in argument). If you want to trim space character(s), while keeping the others (like newline), this answer might be helpful:

sample = '  some string\n'
sample_modified = sample.strip(' ')

print(sample_modified)  # will print 'some string\n'

strip([chars]): You can pass in optional characters to strip([chars]) method. Python will look for occurrences of these characters and trim the given string accordingly.


回答 3

起始文件:

     line 1
   line 2
line 3  
      line 4 

码:

with open("filename.txt", "r") as f:
    lines = f.readlines()
    for line in lines:
        stripped = line.strip()
        print(stripped)

输出:

line 1
line 2
line 3
line 4

Starting file:

     line 1
   line 2
line 3  
      line 4 

Code:

with open("filename.txt", "r") as f:
    lines = f.readlines()
    for line in lines:
        stripped = line.strip()
        print(stripped)

Output:

line 1
line 2
line 3
line 4

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。