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

Time:10-21

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, then at the fourth index it is "s". I am not able to make the code for this.

This is how I tried to do it:

def character(string):
  for x in range(len(string)):
    print(character[3:4])
  return

string = "I Was Told There'd Be Cake"
character(string)

And closely related to this, I am also wondering how to make a function which takes in a list of strings, looks through it, and then returns the last two character of each 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:

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

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.

EDIT:
In case we wanted to use lists instead of a sentence in the second function:

from typing import List

def last_two(list_input: List) -> str:
  result: str = ""
  for word in list_input:
    result  = word[-2:]
  return result

print(last_two(["Apple", "microsoft", "Amazon"]))

CodePudding user response:

this works perfect:

import math

string = "I Was Told There'd Be Cake"
def character(string):
  for i in range(math.ceil(len(string)/4)):
    print(string[i*4])
  return


character(string)
  • Related