python every second char in string code example
Example: how to extract every alternate letters from a string in python?
# Method 1
s = 'abcdefg'
b = ""
for i in range(len(s)):
if (i%2)==0:
b+=s[i]
print(b)
# Output 1
>>> 'aceg'
# Method 2
s = 'abcdefg'[::2]
print(s)
# Output 2
>>> 'aceg'
# Method 3
s = 'abcdefg'
b = []
for index, value in enumerate(s):
if index % 2 == 0:
b.append(value)
b = "".join(b)
print(b)
# Output 3
>>> 'aceg'
# Method 4
s = 'abcdefg'
x = "".join(s[::2])
print(x)
# Output 4
>>> 'aceg'