2024-04-24 23:28:09 发布
网友
使用python3,如何编写一个程序来访问字符串中的第一个字母/字符,如果在字符串的其余部分重复,则返回yes
def first_letter_repeats(string): # returns true or false as output return string[0] in string[1:] def as_yes_no(string): # same function with yes or no as output bool_ = string[0] in string[1:] # True / False equals 0 / 1 return ['no', 'yes'][bool_] # Results: first_letter_repeats('aaron') # True as_yes_no('aaron') # 'yes' first_letter_repeats('arona') # True as_yes_no('arona') # 'yes' first_letter_repeats('aron') # False as_yes_no('aron') # 'no'
最短的版本是定义lambda函数。 除非你确定你为什么要用它,否则不要用它。你知道吗
>>> first_repeats = lambda x: ['no', 'yes'][x[0] in x[1:]] >>> first_repeats('aaron') 'yes' >>> first_repeats('arona') 'yes' >>> first_repeats('aron') 'no' >>>
只要检查它是否存在
def is_first_letter_repeated(mystring): return mystring[0] in mystring[1:] if mystring else False
您可以在具有索引的字符串上循环
比如:
first_letter = parsed_string[0] for char in parsed_string[1:]: # logic you want to implement # then return true or false based on that logic
最短的版本是定义lambda函数。 除非你确定你为什么要用它,否则不要用它。你知道吗
只要检查它是否存在
您可以在具有索引的字符串上循环
比如:
相关问题 更多 >
编程相关推荐