简体   繁体   English

如何在python中删除字符串前后的字符?

[英]How to you remove characters before and after a string in python?

How do I remove the whitespace and strip of the newline carriage return from a string? 如何从字符串中删除换行符回车符的空格和小节​​? I tried: 我试过了:

a = []
for i in range(len(lines)):
     a.append(lines[i].rstrip().lstrip('\n'))

lines is a list of lines that was created with the readlines() function. lines是使用readlines()函数创建的行的列表。

str.strip() removes all whitespace from either side of a string, so the easiest way to do what you want is simply: str.strip()从字符串的任一侧删除所有空格,因此执行所需操作的最简单方法是:

with open("source.txt") as file:
    a = [line.strip() for line in file]

The problem with your code is you are using str.lstrip() and str.rstrip() the wrong way around - the newline is on the right, but you are trying to strip it from the left. 代码的问题是您使用了错误的方式使用str.lstrip()str.rstrip() -换行符在右侧,但是您尝试从左侧剥离它。 The newline gets stripped as the str.rstrip() strips all whitespace from the right (including newlines), while the str.lstrip("\\n") finds no newline character from the left and so does nothing, hence your problem. str.rstrip()从右边剥离所有空格(包括换行符)时,换行符将被剥离,而str.lstrip("\\n")从左边没有找到换行符,因此什么也没做,这就是您的问题。

If you need to leave trailing whitespace except the newline, then you would want line.rstrip("\\n").lstrip() - swapping the arguments for the left and right strips from your original code. 如果您需要保留换行符以外的尾随空白,则需要line.rstrip("\\n").lstrip() -交换原始代码中左右条带的参数。 This would ensure no whitespace other than the newline is stripped, as it would be with the above code. 这样可以确保除换行符外没有其他空格,就像上面的代码一样。

Note that I use a list comprehension to do this - it's both more readable and efficient, and a good way to do tasks like this. 请注意,我使用列表推导来执行此操作-既可读又高效,并且是执行此类任务的好方法。

I also loop directly over the file object, as that is more efficient (the lines do not have to be loaded into memory). 我也直接在文件对象上循环,因为这样做效率更高(行不必加载到内存中)。 Note my use of the the with statement to open files - this is a best practice in Python as it protects you from subtle bugs, and is (again) more readable 注意我使用with语句打开文件-这是Python中的最佳做法,因为它可以保护您免受细微的错误影响,并且(再次)更具可读性

a = [line.strip() for line in lines]

我认为最好在将其放入行列表之前进行剥离

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM