在python中如何遍历字符串进行首位交换?

Python013

在python中如何遍历字符串进行首位交换?,第1张

直接使用字符切片就可以实现:

s = "Thereisastringword"

# 最后一位 + 去头去尾的部分 + 首字符

s1 = s[-1] + "".join(s[1:-1]) + s[0]

print(s1)

用循环也需要等循环结束了再拼接一次字符串

s = "Thereisastringword"

s1 = ""

for i in range(len(s)):

  if i == 0:

      lastword = s[i]

  elif i == len(s) -1 :

      fristword = s[i]

  else:

      s1 += s[i]

print(fristword + s1 + lastword)

总共六个字符

python可以通过str*2重复输出字符串printstr*2#输出字符串两次,循环代码块就是将取到的每个字符进行打印输出,总共六个字符,就循环执行了6次。接下来我们使用For循环遍历一个列表。