How to Split, Concatenate and Join Strings in Python


This example helps us learn some basic methods of handling strings in Python.

Source Code

#! /usr/bin/env python3
# -*- coding: utf-8 -*-

print('Splitting without parameters')
str1 = "This is my home"
str2 = str1.split() # split by space
print(str2)

print('nSplitting with parameters:')
str1 = "1345645615fdsafdsa"
str2 = str1.split('5')
print(str2)

print('nSplitting with maxsplit:')
str2 = str1.split('5', maxsplit=1)
print(str2)

print('nConcatenating with + operator:')
str1 = "hello"
str2 = ", "
str3 = "world"
str4 = "!"
print(str1+str2+str3+str4)

print('nConcatenating with join() function:')

words = ["hello", "world"]
print(", ".join(words))

Output:

Splitting without parameters
['This', 'is', 'my', 'home']

Splitting with parameters:
['134', '64', '61', 'fdsafdsa']

Splitting with maxsplit:
['134', '645615fdsafdsa']

Concatenating with + operator:
hello, world!

Concatenating with join() function:
hello, world
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments