Week-7-2
Splitting and Joining Strings
Overview of String Manipulation
Strings can be split into smaller parts using the
split
method.Key concepts: Token and Separator.
A token is a substring of a larger string.
A separator is a character that divides these tokens in a string.
Splitting Strings
Example string:
music artist song.mp3
.Separator (slashes) divides the string into parts:
music
,artist
,song.mp3
.Usage of
split
:Syntax:
string.split(separator)
.Returns a list of tokens.
Implicit Separator - Whitespace
Example: When using a string like "I love Python", the default separator is white space.
Result after split:
['I', 'love', 'Python']
.
Splitting URLs
URL Example:
https://example.com/path/to/resource
.Split by
/
to get:['https:', '', 'example.com', 'path', 'to', 'resource']
.Consecutive slashes yield empty strings.
A single slash at the beginning or end also yields an empty string.
Joining Strings
The
join
method is the opposite of split, used to combine a list of strings.Syntax:
separator.join(list_of_items)
.Example:
Given a list:
['music', 'artist', 'song.mp3']
Using
join
:'/'.join(list_of_items)
results in:music/artist/song.mp3
.
Joining with a Loop
Alternative to
join
: using a for loop.Initialize an empty string and add each item in the list together:
sentence = "" for phrase in phrases: sentence += phrase
This concatenates without a separator, giving a combined string.
Replacing Separators
Demonstration of replacing separators:
Prompting user for a path and a new separator.
Split at the original separator:
tokens = original_string.split(original_separator)
.Join with the new separator:
new_string = new_separator.join(tokens)
.Example:
file/path
replaced withfile\path
.
Practical Example
Changing from Unix-like paths to Windows-type paths:
file/path
becomesfile\path
.
Checker for Integer Strings
Task: Input string should output "yes" if all characters are digits.
Implementation:
Using the
isDigit()
method to check if all characters are numerical.Code Example:
input_string = input("Enter a string:") if input_string.isdigit(): print("yes") else: print("no")
Example outputs:
Input: "145" -> Output: "yes"
Input: "1,450" -> Output: "no" (comma is not a digit).
Conclusion
Understanding
split
andjoin
methods facilitates string manipulation and management.Practical applications include parsing paths and verifying string formats.