ITPub博客

首页 > > > 如何在Python中反转字符串

如何在Python中反转字符串

作者:choubou 时间:2019-10-08 09:56:42 0 删除 编辑

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

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/4548/viewspace-3160710/ ,如需转载,请注明出处,否则将追究法律责任。

下一篇: !新人求教!
请登录后发表评论 登录
全部评论

注册时间:2019-10-08

  • 博文量
    175
  • 访问量
    10709