可以使用正则表达式找到符合条件的单词,然后对其进行翻转。
代码示例:
import re
def reverse_word_with_capital_and_number(word): pattern = r'^[A-Z][a-zA-Z]*[0-9]$' # 匹配以大写字母开头,以数字结尾的单词 if re.match(pattern, word): return word[::-1] # 翻转单词 else: return word
print(reverse_word_with_capital_and_number('World1')) print(reverse_word_with_capital_and_number('Apple')) print(reverse_word_with_capital_and_number('ABcD2'))