您需要toggle您的狀態;每當你找到一個*
你反轉你的函數的狀態,以便您可以在遍歷文本時在大寫和小寫之間切換。
你可以用not
最簡單的做到這一點; not a
將返回True
如果是False
,反之亦然:
def trans(s):
x = ""
a = False
for j in range(len(s)):
if s[j] == "*":
a = not a # change state; false to true and true to false
continue # no need to add the star to the output
if a:
x += s[j].upper()
else:
x += s[j]
return x
每次找到一個*
字符,a
被觸發;通過在當時使用continue
,還可以防止將*
字符添加到輸出中,因此可以完全避免replace()
。調用一個字符串的''.join()
再次產生相同的字符串,在這種情況下不需要。
這裏您不需要range()
,您可以直接循環播放s
。你可以使用更好的名稱太:
def trans(string):
result = ""
do_upper = False
for character in string:
if character == "*":
do_upper = not do_upper # change state; false to true and true to false
continue # no need to add the star to the output
result += character.upper() if do_upper else character
return result
演示:
>>> def trans(string):
... result = ""
... do_upper = False
... for character in string:
... if character == "*":
... do_upper = not do_upper # change state; false to true and true to false
... continue # no need to add the star to the output
... result += character.upper() if do_upper else character
... return result
...
>>> trans('S*t*a*r*s are every*where*')
'STaRs are everyWHERE'
在星號中,'t'和'r'也改爲大寫字母? – 2015-04-04 12:08:46
@upaangsaxena:是的,因爲他們直接追隨星星。 – 2015-04-04 12:10:02
現在它清楚:) – 2015-04-04 12:13:59