Detail string inversion in Golang and python

  • 2020-06-12 09:55:08
  • OfStack

Detail string inversion in Golang and python

In go, you need to use rune because it involves Chinese or one or more characters with ASCII encoding greater than 255.


func main() {

  fmt.Println(reverse("Golang python"))

}
func reverse(src string) string {
  dst := []rune(src)
  len := len(dst)
  var result []rune
  result = make([]rune, 0)
  for i := len - 1; i >= 0; i-- {
   result = append(result, dst[i])
  }
  return string(result)
}

In python, there are several methods, one is the operation of list, one is the built-in function of the system, and one adopts the above traversal method


# methods 1--------------------------------------
s = 'Golang python'
print (s[::-1])

# methods 2--------------------------------------
s = 'Golang python'
l = list(s)
l.reverse()
print (''.join(l) )

# methods 3--------------------------------------
s = 'Golang python'
str=[]
k=0
for i in s:
  str.append(s[len(s)-1-k])
  k=k+1
print (''.join(str) )

# methods 4--------------------------------------
s = 'Golang python'
str=[]
for i in s:
  str.insert(0,i)
print (''.join(str) )

Above is the explanation of string inversion in Golang and python, if you have any questions, you can leave a message, or go to the community discussion site, thank you for reading, I hope to help you, thank you for your support to this site!


Related articles: