字符串反转

方法一:使用内置函数(切片)

思路:利用Python的切片特性直接反转字符串。

python 复制代码
def reverse_string_with_slice(s):
    return s[::-1]

# 测试
s = "hello"
print(reverse_string_with_slice(s))

方法二:双指针法

思路:将字符串转为列表,用左右指针交换字符直到中间。

python 复制代码
def reverse_string_with_two_pointers(s):
    s = list(s)
    left, right = 0, len(s) - 1
    while left < right:
        s[left], s[right] = s[right], s[left]
        left += 1
        right -= 1
    return ''.join(s)

# 测试
s = "hello"
print(reverse_string_with_two_pointers(s))

方法三:使用内置的 reversed() 函数

reversed() 函数可以返回一个反向迭代器,将其结果转换为字符串即可实现反转。

python 复制代码
def reverse_s(s):
    return ''.join(reversed(s)). 

# ''.join(reversed(s)) 这一步就利用 join 方法把这个反向迭代器里的元素连接成了一个完整的反转字符串。
#reversed(s) 返回的是一个 reversed 类型的迭代器对象,而不是具体的反转字符串内容
<reversed object at 0x7f8d1d8a0d30>


# 测试
s = "hello"
print(reverse_s(s))
相关推荐
u***32433 小时前
使用python进行PostgreSQL 数据库连接
数据库·python·postgresql
青瓷程序设计6 小时前
动物识别系统【最新版】Python+TensorFlow+Vue3+Django+人工智能+深度学习+卷积神经网络算法
人工智能·python·深度学习
tobebetter95276 小时前
How to manage python versions on windows
开发语言·windows·python
F_D_Z6 小时前
数据集相关类代码回顾理解 | sns.distplot\%matplotlib inline\sns.scatterplot
python·深度学习·matplotlib
daidaidaiyu7 小时前
一文入门 LangGraph 开发
python·ai
不知更鸟8 小时前
前端报错:快速解决Django接口404问题
前端·python·django
4***72138 小时前
【玩转全栈】----Django模板语法、请求与响应
数据库·python·django
梁正雄8 小时前
1、python基础语法
开发语言·python
ituff9 小时前
微软认证考试又免费了
后端·python·flask
梁正雄10 小时前
2、Python流程控制
开发语言·python