简体   繁体   中英

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

So I have these text files that contains metadata, and I made this code that prints each line of it (of the first metadata file):

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 ="")

Now the problem is that the fourth and fifth line looks like this in my metadata file

1.0
4.0

So what happens when I print it is that I get:

Blue sky
Blue Ice
Rounded Rectangle
1.0
4.0

How can I remove the last two character (So the.0) of these one?

You can do this,

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 ="")

Or you can just do this

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 ="")

You could use a regex replacement to strip off trailing .0 :

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

The above will actually strip any decimal component. If you really want to target only trailing .0 , then use \.0$ .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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