Home > OS >  How to take out every fourth character in a string and print out?
How to take out every fourth character in a string and print out?

Time:10-20

hey (sorry bad english) The question might sound a little weird, but am going to try and explain it more clear: So how can i make a function that takes in a string and returns every fourth character in that string. so if the string was "I Was Told There'd Be cake" the return would be: (Islh'ek) here you can see the "I" is the first letter than at the fourth index its "s" i can't seem too make the code for this this is how i tried to do it:

string = "I Was Told There'd Be Cake"
def character(string):
for x in range(len(string)):
    print(character[3:4])
return
character(string)

and closly related too this i am also wondering how to make a function again which takes in a string and looks threw it and than returns the last two character of a word. so if the list was ["Apple", "Microsoft", "Amazon"] the outcome would be: (lefton)

CodePudding user response:

my_string = "I Was Told There'd Be Cake"

def my_function(string):
    result_string = ""
    i = 0
    while i <= len(string) - 1:
        if string[i] != "":
            result_string  = string[i]
        i  = 4
    return result_string

print(my_function(my_string))

CodePudding user response:

These functions should do the trick:

def fourth(s: str) -> str:
  result: str = ""
  for i in range(len(s)):
    if i % 4 == 0:
      result  = s[i]
  return result

def last_two(s: str) -> str:
  result: str = ""
  for word in s.split(" "):
    result  = word[-2:]
  return result

print(fourth("I Was Told There'd Be Cake"))
print(last_two("Apple Microsoft Amazon"))

Note that in the second function we assume that every word is separated by a space character.

CodePudding user response:

You could formulate your code as in the following code snippet.

string = "I Was Told There'd Be Cake"

def character(string):
    for x in range(0, len(string), 4):   # Note the step parameter in the for loop
        print(string[x], end='')
    print('\n')
    return
    
character(string)

Which gives you the following output.

@Una:~/Python_Programs/Cake$ python3 Cake.py 
Islh'ek

Give that a try and see if it meets the spirit of your project.

CodePudding user response:

Try:

s = "I Was Told There'd Be cake"

print("".join(s[::4]))

Prints:

Islh'ek
  • Related