String and list

Hi guys. I searched but I couldn’t find the answer. I would like to know how to invert the reading mode, for example in python if you have the phrase = “lua”, just make the phrase [-1: -4: -1], and the result would be aul. But I don’t know how to do this on Julia. Can anybody help me?. Thanks :slight_smile:

julia> s="hey"
"hey"

julia> s[end:-1:begin]
"yeh"

julia>    

Another solution is reverse("lua")

2 Likes

This will fail for non-ascii strings:

julia> s = "αβγδϵhelloω"
"αβγδϵhelloω"

julia> s[end:-1:begin]
ERROR: StringIndexError("αβγδϵhelloω", 10)

Instead use reverse:

julia> reverse(s)
"ωollehϵδγβα"
7 Likes

If you want to reverse indices, you can also use Iterators.reverse on eachindex(s). In general, Iterators.reverse is the non-allocating way to reverse a collection. (In contrast, Base.reverse allocates the reversed collection, but works on fewer iterable types.)

julia> s = "αβγδϵhelloω"
"αβγδϵhelloω"

julia> [s[i] for i in Iterators.reverse(eachindex(s))]
11-element Array{Char,1}:
 'ω'
 'o'
 'l'
 'l'
 'e'
 'h'
 'ϵ'
 'δ'
 'γ'
 'β'
 'α'

julia> join(s[i] for i in Iterators.reverse(eachindex(s)))
"ωollehϵδγβα"

julia> collect(Iterators.reverse(eachindex(s)))
11-element Array{Int64,1}:
 16
 15
 14
 13
 12
 11
  9
  7
  5
  3
  1

3 Likes