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

  • 本文关键字:字符串 range vs python
  • 更新时间 :
  • 英文 :


下面是我要回答的问题:

给定一个字符串和一个非负整数n,返回一个较大的字符串是原始字符串的n个副本。

字符串_times('Hi',2)→ 'HiHi’

字符串_times('Hi',3)→ 'HiHiHi’

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

我的解决方案是:

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

我的问题是,在我的解决方案中,什么都没有*4这一事实会带来什么吗?

此外,你能解释一下使用内置的range()函数是如何成为一个更优雅的解决方案吗?

在以下内容中:

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是上面使用过的更好的选择。

最新更新