my_str.join()
Returns a string after joining elements of any iterable object using any delimiter.
We will use list, dictionary, tuple, set string in our examples.
my_list=['Alex','Ronald','John']
output='*'.join(my_list)
print(output) # Alex*Ronald*John
my_tuple=('Alex','Ronald','John')
output='#'.join(my_tuple)
print(output) # Alex#Ronald#John
my_set={'Alex','Ronald','John'}
output=' '.join(my_set)
print(output) # Alex Ronald John
my_dict={'a':'Alex','b':'Ronald','c':'John'}
output='%'.join(my_dict)
print(output) # a%b%c ( only keys are present ( not values ))
my_str='plus2net'
output='*'.join(my_str)
print(output) # p*l*u*s*2*n*e*t
Using Join to get string from a list with integers
By using join() we are creating strings.
my_str='You have to pass in 3 languages'
my_list=my_str.split(' ')
#print(my_list) # ['You','have','to','pass','in','3','languages']
my_str = ' #'.join(my_list) # from list create string
print(my_str)
Here before using join() we can convert all elements to string by using str. We will apply map() to all elements to convert them to string.
my_list=['You','have','to','pass','in',3,'languages']
my_str = ' #'.join(map(str,my_list)) # from list create string
print(my_str)
This will generate error as we can directly use join() with integers .
my_list=['You','have','to','pass','in',3,'languages']
my_str = ' #'.join(my_list) # from list create string
print(my_str)
TypeError: sequence item 5: expected str instance, int found
« All String methods
← Subscribe to our YouTube Channel here