簡體   English   中英

Strip() function 與 readlines()

[英]Strip() function with readlines()

使用 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

編輯:

這是我從調試中得到的 output:

這是原始字符串: ['pqrm \n', 'google \n', '8'] 嘗試剝離它后,我得到: ["['pqrm \n', 'google \n', '8' ]"] 抱歉,python 或 stackoverflow 不是最好的

您將值列表作為字符串發送,而不是一個一個地發送每個值。 所以試試這個...

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

print(lines)

可以使用 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