Python for循环查找字符并在该字符之前/之后添加子字符串

时间:2018-10-21 23:57:31

标签: python

我是编程的新手,并且正在滑铁卢大学的计算机科学界工作,并且坚持进行以下练习:https://i.stack.imgur.com/ltVu9.png 图像中的代码是我到目前为止提出的。

本练习希望我从“ +”字符之前和之后获取子字符串,并使用for循环将它们添加在一起,但我不知道如何获取子字符串。到目前为止,我已经尝试过

print(S[0:len(char)])

4 个答案:

答案 0 :(得分:1)

要获取'+'符号之前和之后的字符的子字符串,您需要获取'+'char当前位置之前和之后的字符。

S = '12+5'
for pos in range(len(S)):
    char = S[pos]
    if char == '+':
        sub_1 = S[:pos] # Get string before pos
        sub_2 = S[pos + 1:] # Get string after pos
        print('{} + {}'.format(sub_1, sub_2))

# Output: 12 + 5

但是,如果您只是想要最简单的解决方案而不考虑手动操作,那么就像其他人所说的那样,使用.split()会使事情变得简单。由于.split()会将字符串拆分为由特定字符分隔的字符串列表。

使用.split(),代码可以像这样:

S = '12+5'
split_S = S.split('+')  # Creates a list of ['12', '5']
# Make sure our list has 2 items in it to print
if len(split_S) == 2:
    print('{} + {}'.format(split_S[0], split_s[1])

# Output: 12 + 5

答案 1 :(得分:0)

我建议这样做:

nums = S.split('+')
print(int(nums[0])+int(nums[1]))

答案 2 :(得分:0)

sum([int(c) for c in input().split('+')])

5+12
Out: 17

答案 3 :(得分:0)

Epicdaface25是正确的,您可以简单地使用

exclusive

但是,如果您需要使用import numpy as np # set up matrix x = np.zeros((5,5)) # add a single point x[2,-1] = 1 # get coordinates of point as array r, c = np.where(x) # convert to python scalars r = r[0] c = c[0] # get boundaries of array m, n = x.shape coords = [] # loop over possible locations for i in [-1, 0, 1]: for j in [-1, 0, 1]: # check if location is within boundary if 0 <= r + i < m and 0 <= c + j < n: coords.append((r + i, c + j)) print(coords) >>> [(1, 3), (1, 4), (2, 3), (2, 4), (3, 3), (3, 4)] 循环,那么Karl的答案是更好的选择。但是,您不会

nums = S.split('+')
print(int(nums[0])+int(nums[1]))

您需要打印for才能让Python实际上将两个数字相加并显示总和,而不是数学表达式。

相关问题