1.请至少用一种方法实现下面字符串的反转 hello world --> dlrow olleh(整体反转) hello world --> olleh dlrow(按单词反转)
str = 'hello world'
hello world --> dlrow olleh(整体反转)
1.切片
str1 = str[::-1]
print(str1)
2.遍历字符串
str2 = ''
i = len(str)-1
while i >= 0:
str2 += str[i]
i -= 1
print(str2)
hello world --> olleh dlrow(按单词反转)
1、遍历切割后列表切片
str3 = str.split()
str4 = ''
for i in range(0, len(str3)):
str4 += str3[i][::-1]+' '
i += 1
print(str4)
2、循环遍历字符串
str2 = ''
for i in str:
if i is' ':
index = str.find(i)
#找到空字符 那么先将 之前的字符 反转
j = index -1
while j >= 0:
str2 += str[j]
j -= 1
str2 += ' '
#之后的字符 反转
n = len(str)-1
while n >= index+1:
str2 += str[n]
n -= 1
print(str2)

浙公网安备 33010602011771号