YHKIM
YHKIM

Reputation: 1

How to delete specific char and space in python

I want to get 59,000 but I can't get what I want.

a='5M 9,000'
a.strip('M')

Upvotes: 0

Views: 48

Answers (3)

eroc123
eroc123

Reputation: 640

Delete a single char at a specified location

a = '5M 9,000'
a = a[:c]+a[c+1:]

where c is the location of the char

For deleting multiple chars starting from a specified location

a = '5M 9,000'
a = a[:c]+a[c+length:]

where length is the number of chars you want to remove starting from the location c

a = '5M 9,000'
c = 3
a = a[:c]+a[c+1:]

a will be '5M ,000'

a = '5M 9,000'
c = 3
length = 2
a = a[:c]+a[c+length:]

a will be '5M 000'

making it into 59,000

a = '5M 9,000'
c = 1
length = 2
a = a[:c]+a[c+length:]

output a is '59,000'

Upvotes: 0

Sachin Kohli
Sachin Kohli

Reputation: 1986

import re
a = '5M 9,000'
"".join(re.findall(r'\d+', a))

# 59000

or if want output with comma;

"".join([i for i in a if i.isnumeric() or i == ","])

# 59,000

Upvotes: 1

Rakshith B S
Rakshith B S

Reputation: 45

You can use Regex module's sub() function, this returns a string where all matching occurrences of the specified pattern are replaced by the replace string.

Note:- '\D' is used to match all decimals, i think you're trying to extract numbers from the string?

 import re
 a = '5M 9,000'
 a=re.sub(r'\D', '', a)#59000
 print(f'{int(a):,}')

OUTPUT

59,000

Upvotes: 1

Related Questions