Saturday, August 31, 2019

IslandT: Combine two strings with Python method

In this example, we are going to create a method which will do the followings:-

  1. Extract unique characters from two strings then group them into two separate lists.
  2. Create a new list consists of the characters in those two lists. The character within the list must only appear once and only consists of lowercase a-z characters.

Below is the solution.

  1. Create two lists with non-repeated characters from the given two strings.
  2. Loop through all the lowercase characters (from a-z) and if this character appears within any of those two lists then appends them to a new character list.
  3. Turn that new list into a string and then returns that new string.
import string
def longest(s1, s2):
    
    s1 = list(set(s1))
    s2 = list(set(s2))
    s3 = []

    for character in string.ascii_lowercase:
        if character in s1 or character in s2:
            s3.append(character)
    return ''.join(s3)

We will use the string module ascii_lowercase list property to save all the typing we need in order to create the lowercase letters list.

Homework :

Create a new string which only consists of non-repeated digits in the ascending order from two given strings. For example, s1 = “agy569” and s2 = “gyou5370” will produce s3 = “035679”. Write your solution in the comment box below this article.

Do you finish the homework all by your own?



from Planet Python
via read more

No comments:

Post a Comment

TestDriven.io: Working with Static and Media Files in Django

This article looks at how to work with static and media files in a Django project, locally and in production. from Planet Python via read...