Python中没有规定内置函数来反正字符串,如果我们需要反转字符串要怎么办呢。
最简单的方法就是使用向后移动的切片,例如我们要反转字符串hello
:
str1 = "hello"
print("输出反转后的字符串:", str1[::-1])
# 输出反转后的字符串: olleh
创建一个函数
如果多个地方的字符串都需要用到反转字符串,可以创建一个带参函数。
# 创建一个以字符串作为参数的函数
def inverting_fun(x):
# 从字符串末尾开始切割字符串并向后移动
return x[::-1]
# 使用字符串作为参数调用函数
fun = inverting_fun("This is a function for inverting strings")
print(fun)
# sgnirts gnitrevni rof noitcnuf a si sihT
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。