在Python中重复字符串而不进行乘法

2024-04-24 23:04:50 发布

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

enter image description here

你好,我的任务如上图所示。我不是在问答案,我只是想知道如何着手解决这个问题。
我最初的想法是:
1让用户输入str(“示例词”)
2让用户输入int(“示例编号”)
三。使用for循环读取数字,然后打印出单词。你知道吗

到目前为止,我的代码如下所示:

def repeat():
    word=str(input("Please input a single word: "))
    number=int(input("Please input a number: "))
    for i in range(number):
        number+=1
        print(word,end=" ",sep='')
repeat()

但是我遇到了两个问题:
1当打印出单词时,输出是“hello”而不是“hellohello”
2我觉得这个问题我说得不对。你知道吗

如果有任何帮助,我将不胜感激!你知道吗


Tags: 答案代码用户示例numberforinput数字
3条回答

更具python风格的是使用生成器表达式:

def f(s,n):
    return ''.join(s for _ in range(n))

或Python的标准库:

import itertools as it
def f(s, n):
    return ''.join(it.repeat(s, n))

print(f('Hi', 3))

两者都产生

'HiHiHi'

您可以创建如下函数来重复字符串:

def repeat(text, occurrence):
    new_text = ''
    for i in range(occurrence):
        new_text += text
    return new_text

print(repeat('Hi', 4))  # sample usage

最后,您可以实现如下代码:

In [6]: repeat(input("Please input a single word: "), int(input("Please input a number: ")))
Please input a single word: hello
Please input a number: 5
Out[6]: 'hellohellohellohellohello'

这部分代码:

print(word, end=' ', sep='') 

正在添加这些空间。你不需要这些。另外,我不知道为什么要增加'number'数据类型。不需要这样做,因为您只在for循环根据用户输入运行的次数内使用它。此外,这应该传递给一个有两个参数的函数:一个接受和整数,另一个接受字符串。例如:

repeat(intA, strB)

另外,我的建议是连接。将字符串添加到一起,而不是只显示多次。这还允许您创建一个新变量,该变量稍后将返回给调用它的函数。你知道吗

相关问题 更多 >