python每次循环取一个字符,Python - 使用for循环而不是Split方法或任何其他方法提取子字符串...

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:

Write a program that takes a single input line of the form «number1»+«number2», where both of these represent positive integers, and outputs the sum of the two numbers. For example on input 5+12 the output should be 17.

The first HINT given is

Use a for loop to find the + in the string, then extract the substrings before and after the +.

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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值