Python中没有规定内置函数来反正字符串,若是咱们须要反转字符串要怎么办呢。函数
最简单的方法就是使用向后移动的切片,例如咱们要反转字符串hello
:code
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