簡體   English   中英

如何刪除列表中特定元素的最后兩個字符?

[英]How can I remove the last two characters of a specific element in my list?

所以我有這些包含元數據的文本文件,我制作了這段代碼來打印它的每一行(第一個元數據文件的):

path = 'C:\\Users\\basse\\Pictures\\OneM\\metadata\\P5JS metadata\\Metadata'

with open(path + '1.txt') as file:
    lines = []
    for line in file:
        lines.append(line)


print(lines[0], end ="")
print(lines[1], end ="")
print(lines[2], end ="")
print(lines[3], end ="")
print(lines[4], end ="")

現在的問題是第四行和第五行在我的元數據文件中看起來像這樣

1.0
4.0

所以當我打印它時會發生什么:

Blue sky
Blue Ice
Rounded Rectangle
1.0
4.0

如何刪除這些字符的最后兩個字符(So the.0)?

你可以這樣做,

with open(path + '1.txt') as file:
    lines = []
    for line in file:
        lines.append(line. replace(".0", ""))

print(lines[0], end ="")
print(lines[1], end ="")
print(lines[2], end ="")
print(lines[3], end ="")
print(lines[4], end ="")

或者你可以這樣做

with open(path + '1.txt') as file:
    lines = []
    for line in file:
        lines.append(line)

print(lines[0], end ="")
print(lines[1], end ="")
print(lines[2], end ="")
print(lines[3].replace(".0", ""), end ="")
print(lines[4].replace(".0", ""), end ="")

您可以使用正則表達式替換來去除尾隨.0

with open(path + '1.txt') as file:
    lines = []
    for line in file:
        lines.append(re.sub(r'\.\d+$', '', line))

以上實際上將去除任何小數部分。 如果您真的只想定位尾隨.0 ,請使用\.0$

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM