简体   繁体   English

Strip() function 与 readlines()

[英]Strip() function with readlines()

With the strip() function the \n does not strip and instead changes the string (I don't know how to describe it, test for yourself)使用 strip() function 时, \n 不会剥离而是更改字符串(我不知道如何描述它,自己测试)

lines = []
line = str(pw.readlines())
print(line)
x = line.strip("\n")
x = line.strip("\t")
lines.append(x)
print(lines)enter code here

edit:编辑:

here is the output I get from debugging:这是我从调试中得到的 output:

here is the original string: ['pqrm \n', 'google \n', '8'] After I try to strip it I get: ["['pqrm \n', 'google \n', '8']"] Sorry not the best with python or stackoverflow这是原始字符串: ['pqrm \n', 'google \n', '8'] 尝试剥离它后,我得到: ["['pqrm \n', 'google \n', '8' ]"] 抱歉,python 或 stackoverflow 不是最好的

You are sending the list of values as a string, instead of each value one by one.您将值列表作为字符串发送,而不是一个一个地发送每个值。 So try this...所以试试这个...

lines = []
for line in pw.readlines():
    x = line.strip("\n").strip("\t")
    lines.append(x)

print(lines)

One can use re.sub, to get rid of newlines, tabs, spaces.可以使用 re.sub 来去除换行符、制表符、空格。

import re

st = "['pqrm \n', 'google \n', '8']"

print(re.sub(r'[\n\t\s]+','', st))

['pqrm','google','8']

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

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