ADVERTISEMENT
ADVERTISEMENT

Python program to split and join a string

Here, we will take input from the user and then print the split and join strings in Python.
Submitted by Shivang Yadav, on April 17, 2021

Python programming language is a high-level and object-oriented programming language. Python is an easy to learn, powerful high-level programming language. It has a simple but effective approach to object-oriented programming.

Strings in Python are immutable means they cannot be changed once defined.

Splitting a string is taking the string and then storing it in a list as a list of words.

Joining string is taking a collection and a separator, and joining all values to a string.

Splitting and joining a string

We will take a string and separator as input from the user. Then print a list created by splitting the string into words. Then we will join them back to a string separated by the separator.

For splitting the string into words, we will use the split() method.

Syntax:

string_name.split(delemitor)

For joining the collection of words into a string with a separator, we will use the join() method.

Syntax:

'separator'.join(collection of string)

Algorithm:

  • Get the string and separator as input from the user.
  • Using the split() method, create a collection of words from the string.
  • Using the join() method, create a string with words separated by a separator.
  • Print both the values.

Program to split and join a string

# Python program to split and join string 

# Getting input from user 
myStr =  input('Enter the string : ')
separator = input('Enter the separator : ')

# splitting and joining string 
splitColl = myStr.split(' ')
joinedString = separator.join(splitColl)
		
# printing values
print(splitColl)
print(joinedString)

Output:

Enter the string : learn python programming at include help
Enter the separator : /
['learn', 'python', 'programming', 'at', 'include', 'help']
learn/python/programming/at/include/help

Python String Programs »



ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.