Python program to split and join a string?

PythonProgrammingServer Side Programming

Python program provides built in function for string joining and split of a string.

split
Str.split()
join
Str1.join(str2)

Algorithm

Step 1: Input a string.
Step 2: here we use split method for splitting and for joining use join function.
Step 3: display output.

Example code

#split of string
str1=input("Enter first String with space :: ")
print(str1.split())    #splits at space

str2=input("Enter second String with (,) :: ")
print(str2.split(','))    #splits at ','

str3=input("Enter third String with (:) :: ")
print(str3.split(':'))    #splits at ':'

str4=input("Enter fourth String with (;) :: ")
print(str4.split(';'))    #splits at ';'

str5=input("Enter fifth String without space :: ")
print([str5[i:i+2]for i in range(0,len(str5),2)])    #splits at position 2

Output

Enter first String with space :: python program
['python', 'program']
Enter second String with (,) :: python, program
['python', 'program']
Enter third String with (:) :: python: program
['python', 'program']
Enter fourth String with (;) :: python; program
['python', 'program']
Enter fifth String without space :: python program
['py', 'th', 'on', 'pr', 'og', 'ra', 'm']

Example Code

#string joining
str1=input("Enter first String   :: ")
str2=input("Enter second String  :: ")
str=str2.join(str1)     #each character of str1 is concatenated to the #front of str2
print(“AFTER JOINING OF TWO STRING ::>”,str)

Output

Enter first String   :: AAA
Enter second String  :: BBB
AFTER JOINING OF TWO STRING ::>ABBBABBBA
raja
Published on 24-Sep-2018 13:09:30
Advertisements