Home > Software engineering >  Swap last two characters in a string, make it lowercase, and add a space
Swap last two characters in a string, make it lowercase, and add a space

Time:07-02

I'm trying to take the last two letters of a string, swap them, make them lowercase, and leave a space in the middle. For some reason the output gives me white space before the word.

For example if input was APPLE then the out put should be e l

It would be nice to also be nice to ignore non string characters so if the word was App3e then the output would be e p

def last_Letters(word):
    
    last_two = word[-2:]
    swap = last_two[-1:]   last_two[:1]
    
    for i in swap:
        if i.isupper():
            swap = swap.lower()
    
        return swap[0]  " "  swap[1]
    
    
word = input(" ")
print(last_Letters(word))

CodePudding user response:

You can try with the following function:

import re

def last_Letters(word):
    letters = re.sub(r'\d', '', word)
    if len(letters) > 1:
        return letters[-1].lower()   ' '   letters[-2].lower()
    return None

It follows these steps:

  • removes all the digits
  • if there are at least two characters:
    • lowers every character
    • builds the required string by concatenation of the nth letter, a space and the nth-1 letter
    • and returns the string
  • returns "None"

CodePudding user response:

Since I said there was a simpler way, here's what I would write:

text = input()
result = ' '.join(reversed([ch.lower() for ch in text if ch.isalpha()][-2:]))
print(result)

How this works:

  • [ch.lower() for ch in text] creates a list of lowercase characters from some iterable text
  • adding if ch.isalpha() filters out anything that isn't an alphabetical character
  • adding [-2:] selects the last two from the preceding sequence
  • and reversed() takes the sequence and returns an iterable with the elements in reverse
  • ' '.join(some_iterable) will join the characters in the iterable together with spaces in between.

So, result is set to be the last two characters of all of the alphabetical characters in text, in reverse order, separated by a space.

Part of what makes Python so powerful and popular, is that once you learn to read the syntax, the code very naturally tells you exactly what it is doing. If you read out the statement, it is self-describing.

  • Related