使用 Python 运算符重复字符串

PythonPythonBeginner
立即练习

This tutorial is from open-source community. Access the source code

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

简介

在 Python 中,我们可以使用 * 运算符将字符串重复特定的次数。这在许多情况下都很有用,例如当我们需要创建具有特定字符数的字符串时,或者当我们需要重复某个模式时。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/DataStructuresGroup(["Data Structures"]) python(("Python")) -.-> python/FunctionsGroup(["Functions"]) python(("Python")) -.-> python/BasicConceptsGroup(["Basic Concepts"]) python/BasicConceptsGroup -.-> python/comments("Comments") python/DataStructuresGroup -.-> python/tuples("Tuples") python/FunctionsGroup -.-> python/function_definition("Function Definition") subgraph Lab Skills python/comments -.-> lab-13698{{"使用 Python 运算符重复字符串"}} python/tuples -.-> lab-13698{{"使用 Python 运算符重复字符串"}} python/function_definition -.-> lab-13698{{"使用 Python 运算符重复字符串"}} end

重复字符串

编写一个名为 repeat_string 的函数,它接受两个参数:一个字符串 s 和一个整数 n。该函数应返回一个新字符串,其中包含重复 n 次的 s

例如,如果 s"hello"n3,则该函数应返回 "hellohellohello"。如果 s"abc"n5,则该函数应返回 "abcabcabcabcabc"

def n_times_string(s, n):
  return (s * n)
n_times_string('py', 4) #'pypypypy'

总结

在这个挑战中,你学习了如何使用 * 运算符将字符串重复特定的次数。你还编写了一个名为 repeat_string 的函数,它以字符串和整数作为参数,并返回一个新字符串,其中包含重复 n 次的原始字符串。