Home > Software design >  How to get every second element/character from a string in python?
How to get every second element/character from a string in python?

Time:10-28

I've this string: mystr = 'one two three four five six' and I want to get every second element from a string. So the output I want is: 'two four six' Because eventually I want the output to be as: 'one owt three ruof five xis' i.e; I want to reverse every second element from the string and that's why I'm fetching every second element from a string. Can you please help me with it?! Thank you in advance!

Don't mind but this what I was trying;

mystr = 'one two three four five six'
mystr.split(" ")
# print(type(mylist))
# print(len(mylist))
mylist = list(mystr)
print((mylist))
print(len(mylist))

CodePudding user response:

mystr = "one two three four five six"
temp = mystr.split()
result = []
for i in range(len(temp)):
    if (i   1)%2 == 0:
        result.append(temp[i][::-1])
    else:
        result.append(temp[i])
print(result)

Output:

['one', 'owt', 'three', 'ruof', 'five', 'xis']

CodePudding user response:

For a concise and efficient solution you can use a list-builder notation to create an array where the word is reversed (w[::-1]) at even indices and forwards at odd indices (w). enumerate(some_list) allows you to iterate over the indices and values simultaneously. In this case, we used mystr.split() to split it at the spaces. At the end, all you need to do is join.

mystr = 'one two three four five six'
output = ' '.join([w[::-1] if i % 2 else w for i, w in enumerate(mystr.split())])
print(output)

Output: "one owt three ruof five xis"

As an alternative solution which you may find more readable, but is less consice and less efficient, would be to iterate over a range starting from 1 with a skip of 2, and reverse each word as its index appears in the loop.

mystr = 'one two three four five six'
# split the string into a list of words
words = mystr.split()
# reverse every other word in the list
for i in range(1, len(words), 2):
    words[i] = words[i][::-1]
# join the list back into a string
print(' '.join(words))

Output: "one owt three ruof five xis"

  • Related