J.Salinas
J.Salinas

Reputation: 69

How to convert dollar sign to words in Python

I am looking to format something like "$100" to "100 dollars" using Python.

How can I do this?

I want to do some text processing from a news feed (RSS) using Python NLTK, but first I want to "clean up" that text a bit, so I thought about starting with the dollar signs.

Upvotes: 0

Views: 911

Answers (4)

Yosi Hammer
Yosi Hammer

Reputation: 588

Or use regex:

import re
s = '$100'
s1 = re.sub('\$([0-9]+)', '\g<1> dollars', s)
print(s1) # '100 dollars'

Maybe include decimals:

s = '$100.99'
s1 = re.sub('\$([0-9]+\.?[0-9]*)', '\g<1> dollars', s)
print(s1) # 100.99 dollars

Upvotes: 1

Rabindra Tamang
Rabindra Tamang

Reputation: 1

a= $500
for i in a:
       if i==$:
            continue

       else:
            print(i,end='')
 print("Dollar")

output: 500 dollar

Upvotes: -1

Rahul charan
Rahul charan

Reputation: 837

Use if AND replace method of string to get your desired result.

s = "$100"
if "$" in s:
    s = s.replace('$', "")
    s = s+" dollars"
    print(s)

Output:-

100 dollars

I hope it may help you

Upvotes: 0

U13-Forward
U13-Forward

Reputation: 71610

Try using this if statement:

s = "$100"
if '$' in s:
    print(s[1:] + ' dollar%s' % ('s' if int(s[1:]) != 1 else ''))

Output:

100 dollars

Also, for "$1" it would give 1 dollar without s at the end.

Upvotes: 1

Related Questions