使用乘数vs range()重复字符串

2024-04-20 09:00:11 发布

您现在位置:Python中文网/ 问答频道 /正文

下面是我提出的问题:

Given a string and a non-negative int n, return a larger string that is n copies of the original string.

string_times('Hi', 2) → 'HiHi'

string_times('Hi', 3) → 'HiHiHi'

string_times('Hi', 1) → 'Hi'

我的解决方案是:

def string_times(str, n):

  if str and n >= 0:
   return str*n

结果是:

Expected    Run     
string_times('Hi', 2) → 'HiHi'          
string_times('Hi', 3) → 'HiHiHi'      
string_times('Hi', 1) → 'Hi'     
string_times('Hi', 0) → ''          
string_times('Hi', 5) → 'HiHiHiHiHi'            
string_times('Oh Boy!', 2) → 'Oh Boy!Oh Boy!'           
string_times('x', 4) → 'xxxx'   

string_times('', 4) → ''    None    X     <-- issue 

string_times('code', 2) → 'codecode'      
string_times('code', 3) → 'codecodecode'    

编辑:

这是预期结果:

string_times('', 4) → ''

这是实际结果(如我所说)

string_times('', 4) → None

从我所看到的,我遗漏了等式的“空”部分。你知道吗

给出的解决方案如下:

def string_times(str, n):
  result = ""
  for i in range(n):  # range(n) is [0, 1, 2, .... n-1]
    result = result + str  # could use += here
  return result

我的问题是,在我的解决方案中,事实是什么都不给吗?你知道吗

另外,您能解释一下如何使用内置range()函数将是一个更优雅的解决方案吗?你知道吗


Tags: andstringreturnisdefrangeresult解决方案
1条回答
网友
1楼 · 发布于 2024-04-20 09:00:11

在以下方面:

def string_times(str, n):

  if str and n >= 0:
   return str*n

如果字符串是空的,那么if永远不会返回值,函数从末尾掉下来,返回None-要么添加一个return ''显式返回空白,要么完全删除检查。。。你知道吗

您的整个功能可以是:

def string_times(text, n): 
    return text * n

任何乘以0或更小的字符串都将是空字符串,任何空字符串乘以任何值都将保持空。。。其他一切都会按预期进行。。。我也不会称之为str(最好不要阴影内置)-text是上面使用过的更好的选择。你知道吗

相关问题 更多 >