python使用while字符串反转
时间: 2024-06-13 14:09:38 浏览: 16
以下是使用while循环反转字符串的Python代码:
```python
def reverse_string(s):
# 将字符串转换为列表
s_list = list(s)
# 定义左右指针
left, right = 0, len(s_list) - 1
# 循环交换左右指针对应的字符
while left < right:
s_list[left], s_list[right] = s_list[right], s_list[left]
left += 1
right -= 1
# 将列表转换为字符串并返回
return ''.join(s_list)
# 测试
s = 'I love China!'
print(reverse_string(s)) # 输出:!anihC evol I
```
相关问题
while循环实现字符串反转
以下是使用while循环实现字符串反转的示例代码:
```python
s = "hello world"
length = len(s)
new_str = ""
while length > 0:
new_str += s[length-1]
length -= 1
print(new_str)
```
运行结果为:dlrow olleh
Python反转字符串
Python中有多种方法可以反转字符串,其中一种是使用循环。具体实现方法如下:
```python
string1 = "the crazy programmer"
string2 = ""
i = len(string1) - 1
while(i >= 0):
string2 = string2 + string1[i]
i = i - 1
print("original = " + string1)
print("reverse = " + string2)
```
该方法通过循环遍历字符串中的每个字符,并将其逆序添加到一个新的字符串中,从而实现字符串的反转。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)