Printing Even Characters With Strings in Python

Printing even characters with strings in python

You are trying to iterate through int (len(s))
i think you're just simply missing the range function

s = 'Abrakadabra'
for k in range(len(s)):
if k%2==1:
print(s[k])

also much simlpler version is could be done with:

>>> s[1::2]
'baaar'

let's break it down:

s[1: :2]
^ ^ ^ ^
|-|-|-|--- string to use
|-|-|--- index to start from (1 for even, zero or ' ' for odd)
|-|--- index to stop at - space means "till the end"
|----step to take - 2 for every second, 3 for every third and so on

How to print even and odd chars from a given string in Python

Would you like to try this: (just a sample code to give you hints)

N = len(s)   # your string's len

evens = ''.join(s[i] for i in range(0, N,2)) # 'Hce'

# then do the odds character as well

Extracting characters from even index position

Checking with if is redundant here since range itself has step. Just do it in this way:

s = 'Michael Jordan'
for k in range(0, len(s), 2): # 2 here is the step
print(s[k])

Returning odd or even number of characters from user input

num is not defined. Assign it to the string argument's len:

input_string = str(input("Please enter your name: "))

def evenodd(s):
num = len(s) # <- here!
if num % 2 == 0:
return "even"
else:
return "odd"

print(evenodd(input_string))

I renamed the function argument to illustrate that it is completely independent from the input_string variable in the global scope.

How to find even numbers in a string in Python

You will take expected output with this. All you need to do to replace evenNumbers += number with evenNumbers.append(int_num).

s = "75,41,14,8,73,45,-16"
evenNumbers = []

for number in s.split(","):
int_num = int(number)
if int_num % 2 == 0 and int_num > 0:
evenNumbers.append(int_num)

print("Even Numbers : \"{}\"".format(evenNumbers))

Given the characters in odd position and even position of a string, how can we combine them to get the final string in python?

I think you're looking for

originalstring = ''.join([''.join(x) for x in zip(evenstring, oddstring)])

If the length doesn't match you can do

if(len(oddstring) != len(evenstring)):
originalstring = originalstring + evenstring[-1]


Related Topics



Leave a reply



Submit