python - 使用乘数 vs range() 重复一个字符串

标签 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

我的问题是,在我的解决方案中,nothing*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 是上面使用的更好的选择。

关于python - 使用乘数 vs range() 重复一个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29114609/

相关文章:

python - 关闭当前文件/ View /显示而不保存或被要求这样做

python - 字典优化

python - SyntaxError 无效 token

python - 按轴分数定位文本

python - 在 Python Pylons 中检测 ajax 与常规浏览器帖子

python - socket,gethostbyaddr 的返回和写入文件如何拆分?

python - 在 Python 中解析文件时跳过一行?有什么简单/基本的方法吗?

python - Python 中的关键字到底是什么?

python - 无法在 heroku django 中导入名称 _uuid_generate_random

python - 通过本地Exim MTA用python发送电子邮件