Home > Software design >  How to delete specific char and space in python
How to delete specific char and space in python

Time:10-02

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

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

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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'

  • Related