Skip to main content
 首页 » 编程设计

如果字符串以 "ly"结尾,则将 "ing"添加到字符串结尾的 Pythonic 方法

2025年05月04日23jillzhang

这是我第一次尝试解决这个问题。我得说,我有点喜欢 Python。 :D

# D. verbing 
# Given a string, if its length is at least 3, 
# add 'ing' to its end. 
# Unless it already ends in 'ing', in which case 
# add 'ly' instead. 
# If the string length is less than 3, leave it unchanged. 
# Return the resulting string. 
def verbing(s): 
  if len(s) >= 3: 
    if s[-3:] == "ing": 
      s += "ly" 
    else: 
      s += "ing" 
    return s 
  else: 
    return s  
 
  # +++your code here+++ 
  return 

您认为我可以在这里改进什么?

请您参考如下方法:

def verbing(s): 
  if len(s) >= 3: 
    if s.endswith("ing"): 
      s += "ly" 
    else: 
      s += "ing" 
  return s