[英]How to delete letters [A-Z] with python
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.因为看起来你的单位总是在最后,你可以避免使用正则表达式而只使用
str.rstrip
。
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.模块
string
定义了包含所有 AZ 字符的ascii_uppercase
。
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:正则链接:
https://regex101.com/r/DZIaUM/1 https://regex101.com/r/DZIaUM/1
You might use str
translate
method to get rid of unwanted characters您可以使用
str
translate
方法来摆脱不需要的字符
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. maketrans接受 3 个参数,在这种情况下,第 2 个是空的,因为我们只需要删除字符,而不是替换。 However as you need these unit I suggest using
re
for that following way:但是,当您需要这些单元时,我建议使用
re
进行以下方式:
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')]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.