问题描述
我参加了一个,程序员是使用for循环提取一个子字符串。一年前问了一个,所以问题是:
$ b
给出的第一个提示是
这是我的尝试,我知道是错误的,因为在循环中没有等于+的位置。如何找到'+'在字符串5 + 12中的位置?
pre $ S $ input $
s_len = len(S)
(0,s_len):
如果position =='+':
print(position [0,s_len])
** SPOILER ALERT - 编辑显示任何CSC滑铁卢课程参加者的答案
pre $ s $ input $ b $ s_len = len(S)
(0,s_len):
如果S [position] =='+':
number1 = int(S [0:position])
number2 = int(S [position:s_len])
sum = number1 + number2
print(sum)
c $ c> enumerate ,如果你想用循环来做:
S =输入()
位置,枚举(S)中的字符:
如果字符=='+':
打印(位置)
break#一旦出现字符被发现
枚举
返回iterable / iterator中的索引和项目。
>>>列表(枚举(foobar))
[(0,'f'),(1,'o'),(2,'o'),(3,'b'), a'),(5,'r')]
解决方案的工作版本:
S = input()
s_len = len(S)
在范围(0,s_len)中的位置:
如果S [position] =='+':#使用索引从字符串中获取项目。
print(position)
I'm taking an online Python course which poses a problem where the programmer is to extract a substring using a for loop. There was a similar question asked a year ago, but it didn't really get answered.
So the problem reads:
The first HINT given is
This is my attempt, which I know is wrong because there is no position in the loop where it equals a '+'. How do I find the position where the '+' is in the string "5+12"?
S = input()
s_len = len(S)
for position in range (0,s_len):
if position == '+':
print(position[0,s_len])
**SPOILER ALERT - Edit to show any CSC Waterloo course takers the answer
S = input()
s_len = len(S)
for position in range (0,s_len):
if S[position] == '+':
number1 = int(S[0:position])
number2 = int(S[position:s_len])
sum = number1 + number2
print(sum)
Use enumerate
, if you want to do this using a loop:
S = input()
for position, character in enumerate(S):
if character == '+':
print(position)
break # break out of the loop once the character is found
enumerate
returns both index and the item from the iterable/iterator.
>>> list(enumerate("foobar"))
[(0, 'f'), (1, 'o'), (2, 'o'), (3, 'b'), (4, 'a'), (5, 'r')]
Working version of your solution:
S = input()
s_len = len(S)
for position in range(0, s_len):
if S[position] == '+': #use indexing to fetch items from the string.
print(position)
这篇关于Python - 使用for循环而不是Split方法或任何其他方法提取子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!