Monday, May 24, 2021

Strings - join()

The main focus of this post is join() method.

join method takes all elements of list/tuple and joins them to string.

"-".join(my_list) 

every element in list is joined by a colon and the resulting type is string.

 "character to join the elements".join(my_list) 

is the syntax of join method.

1)Read a given string, change the character at a given index and then print the modified string. 

Input:

abracadabra 

5 k 

Output:

abrackdabra


def mutate_string(string, position, character):
    ns=list(string) #since string is immutable, convert string to list.
    ns[position]=character #change the character at specific position.
    ns="".join(ns) #using join to convert list back to string.
    return ns

if __name__ == '__main__':
    s = input()
    i, c = input().split()
    s_new = mutate_string(s, int(i), c)
    print(s_new)

 

2)Split a line and join the words using "-"

Sample Input

this is a string

Sample Output

this-is-a-string 

def split_and_join(line):
    line=line.split(" ") #output - ["this","is","a","string"]
    return "-".join(line) #converts list back to string.
 
line = input()
result = split_and_join(line)
print(result)

 

split method splits the line into separate elements and result of line=line.split() is a list.

line=line.split(" ")

forms a list with every element in input separated by a space.

line=line.split(",")


forms a list with every element in input separated by a comma.

No comments:

Post a Comment

Anaconda Installation

In this post we will discuss about Anaconda and its installation. Anaconda comes with number of applications(jupyter notebook included), dat...