I want to delete letters from a string and save which is deleted in variable from these lines as below :
Input =
1.785K
10MEG
999.1V
Expected :
Value = 1.785
Units detected = K
Value = 10
Units detected = MEG
Value = 999.1
Units detected = V
I try this code but doens't work
list = ['1.785K','10MEG','999.1V']
for l in list:
l.replace("[A-Z]", "")
print("Value =" + l)
print("Units detected =" )
Because seems like your units are always at the end, you can avoid using regex and just use str.rstrip
instead.
It removes a suffix of characters that can be provided as a string containing all chars to remove. the module string
defines ascii_uppercase
that contains all AZ chars.
as for getting the deleted chars, you can use the length of the stripped string to slice the original string and get exactly the removed chars
try this:
from string import ascii_uppercase
list = ['1.785K','10MEG','999.1V']
for l in list:
after_strip = l.rstrip(ascii_uppercase)
stripped_chars = l[len(after_strip):]
print("Value = " + l)
print("Units detected = " + stripped_chars)
There you go:
I've solved this using regex
import re
input = '''1.785K
10MEG
999.1V
'''
for val,unit in re.findall('([0-9\.]+)([A-Za-z]+)',input):
print('Value : ',val)
print('Units : ',unit)
print()
Output:
Value : 1.785
Units : K
Value : 10
Units : MEG
Value : 999.1
Units : V
Regex link:
You might use str
translate
method to get rid of unwanted characters
import string
t = str.maketrans('','',string.ascii_uppercase)
data = ["1.785K","10MEG","999.1V"]
for d in data:
print(d.translate(t))
Output:
1.785
10
999.1
maketrans accepts 3 arguments, 2 first are empty in this case, because we need only to remove characters, not replace. However as you need these unit I suggest using re
for that following way:
import re
data = ["1.785K","10MEG","999.1V"]
for d in data:
print(re.findall(r'(.*?)([A-Z]+)',d))
Output:
[('1.785', 'K')]
[('10', 'MEG')]
[('999.1', 'V')]
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.