我想将字符串中的数字和运算符分开,怎么办?
我正在使用拆分并获取数字,但无法获取运算符 该代码仅在运算符为'+'时有效,否则会出错!
T = "123+456"
op = '+' or '-'
for i in range(T):
n = input()
n1,n2 = n.split(op)
print(n1)
print(n2)
答案 0 :(得分:3)
您可以使用正则表达式通过r'(\d+)|([+\-\*/])'
查找字符串中存在的数字和运算符,它们匹配一个或多个数字,或者匹配+,-,*,\
之外的运算符
import re
def get_num_op(s):
#Get all matches
matches = re.findall(r'(\d+)|([+\-\*/])', s)
#[('123', ''), ('', '+'), ('456', ''), ('', '*'), ('7', ''), ('', '*'), ('8', '')]
#Remove empty matches from the list
matches = [item for t in matches for item in t if item]
return matches
print(get_num_op("123+456"))
print(get_num_op("123+45*6/7"))
输出将为
['123', '+', '456']
['123', '+', '45', '*', '6', '/', '7']
答案 1 :(得分:2)
您可以使用re
进行拆分:
import re
T = "123+456"
re.split('((\w)[0-9]*)', T)
out:['', '123', '+', '456', '']
答案 2 :(得分:1)
此代码可与"+","-","*","/"
这组运算符配合使用。它将为您提供operand1
,operand2
和operator
。
user_input="12-23"
operator_list = ["+","-","*","/"]
input_list = [x for x in user_input]
for operator in operator_list:
if operator in input_list:
index = input_list.index(operator)
break
operand1 = user_input[:index]
operand2 = user_input[index+1:]
print(operand1 , operator, operand2)
输出
12 - 23