Taimoor Khan
Taimoor Khan

Reputation: 615

Removing decimal place from int or string in Python

I have a text file with a string like 0.0.1 and I want to remove the decimals to make it 001 or just 1. So for example a 1.0.1 would become a 101.

I thought about using the round() but it would turn 0.0.1 into 0 and that's not what I want.

Upvotes: 3

Views: 25549

Answers (3)

Juergen
Juergen

Reputation: 12728

You could just remove the '.' between the digits:

s = '0.0.1'
s = s.replace('.', '')

after that you can make it an int:

int(s)

By making it an integer, you will also remove any leading zeros. If you need a string afterwards just convert it back to string:

s = str(int(s))

Upvotes: 10

Alea Kootz
Alea Kootz

Reputation: 919

Use replace()

Try something like this code block:

new_file = open('newfile.txt','w')

line_file = open('myfile.txt','r').readlines()

for line_in in line_file:
    line_out = line_in.replace('.','')
    new_file.write(line_out)

That should read your file, remove all the periods, and write the result to a new file.

If it doesn't work for your specific case, comment on this answer and I'll update the codeblock to do what you need.

p.s. As per the comment below, you could make this happen in one line with:

open('newfile.txt','w').write(open('myfile.txt','r').read().replace('.',''))

So use that if you want to.

Upvotes: 2

John Coleman
John Coleman

Reputation: 51998

You could use join and a comprehension:

>>> s = '0.0.1'
>>> ''.join(c for c in s if c != '.')
'001'

If you want to strip the leading 0s:

>>> str(int(''.join(c for c in s if c != '.')))
'1'

Upvotes: 2

Related Questions