IWSPythoner

  博客园 :: 首页 :: 新随笔 :: 联系 :: 订阅 :: 管理 ::

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)
 
 
posted on 2017-08-11 16:09  IWSPythoner  阅读(611)  评论(0)    收藏  举报