String manipulation in Python
This article explains string manipulation in Python.
You can learn about various string manipulations, such as creating and concatenating strings, searching, and replacing, along with code samples.
YouTube Video
String manipulation in Python
There are various ways to manipulate strings in Python. Below is an introduction to commonly used string operations.
Creating strings
In Python, strings can be created using single quotes ('
), double quotes ("
), or triple quotes ('''
, """
).
1single_quoted = 'Hello'
2double_quoted = "World"
3multi_line = '''This is
4a multi-line
5string'''
6
7print(single_quoted)
8print(double_quoted)
9print(multi_line)
- This code demonstrates how to create and display strings in Python using single quotes, double quotes, and triple quotes.
String concatenation
To concatenate strings, use the +
operator, f-strings
, or the str.format
method.
1# + operator
2name = "John"
3greeting = "Hello, " + name + "!"
4print(greeting)
5
6# f-string (available in Python 3.6 and above)
7greeting_f = f"Hello, {name}!"
8print(greeting_f)
9
10# str.format method
11greeting_format = "Hello, {}!".format(name)
12print(greeting_format)
- This code shows how to concatenate strings in Python using the
+
operator, f-strings, and thestr.format
method.
Repeating strings
To repeat strings, use the *
operator.
1repeat = "ha" * 3 # Result: "hahaha"
2print(repeat)
- This code demonstrates how to repeat strings in Python using the
*
operator.
Length of a string
To get the length of a string, use the len
function.
1name = "John"
2greeting = "Hello, " + name + "!"
3
4# Returns the length of the string greeting
5length = len(greeting)
6print(length)
- This code shows how to get the length of a string in Python using the
len
function.
Indexing and slicing
Use indexing or slicing to retrieve specific characters or substrings within a string.
1word = "Python"
2
3first_char = word[0] # P
4last_char = word[-1] # n
5print(first_char)
6print(last_char)
7
8# Slice
9sliced_word = word[1:4] # yth
10reversed_word = word[::-1] # nohtyP
11print(sliced_word)
12print(reversed_word)
- This code demonstrates how to retrieve specific characters or substrings from a string in Python using indexing and slicing.
Processing each character
Since strings are treated as sequence types, you can process each character using a for
loop.
1text = "Python"
2
3# Iterate each character
4for char in text:
5 print(char)
- {^ i18n_speak
このコードは、文字列
Python
を1文字ずつ取り出して順番に表示する方法を示しています。^}
Searching and replacing in strings
Use the str.find
and str.replace
methods to search and replace in strings.
1sentence = "She sells sea shells on the sea shore."
2
3# Returns the index of the first occurrence of "sea": 10
4index = sentence.find("sea")
5print(index)
6
7# Replace "sea" with "ocean"
8replaced_sentence = sentence.replace("sea", "ocean")
9print(replaced_sentence)
- This code shows how to search for a string using the
str.find
method and replace a string using thestr.replace
method in Python.
Converting case in strings
To convert strings to uppercase or lowercase, use str.upper
, str.lower
, str.capitalize
, or str.title
.
1text = "hello world"
2upper_text = text.upper() # "HELLO WORLD"
3lower_text = text.lower() # "hello world"
4capitalized_text = text.capitalize() # "Hello world"
5title_text = text.title() # "Hello World"
6
7print(upper_text)
8print(lower_text)
9print(capitalized_text)
10print(title_text)
- This code demonstrates how to convert strings to uppercase, lowercase, and title case in Python.
Splitting and joining strings
To split a string by a specific delimiter, use str.split
, and to join elements of a list, use str.join
.
1csv = "apples,bananas,cherries"
2fruits = csv.split(",") # ["apples", "bananas", "cherries"]
3joined_fruits = ", ".join(fruits) # "apples, bananas, cherries"
4
5print(fruits)
6print(joined_fruits)
- This code shows how to split a string using
str.split
and join list elements usingstr.join
in Python.
Removing whitespace
To remove whitespace from a string, use str.strip
, str.lstrip
, or str.rstrip
.
1whitespace = " hello "
2stripped = whitespace.strip() # "hello"
3lstripped = whitespace.lstrip() # "hello "
4rstripped = whitespace.rstrip() # " hello"
5
6print(stripped)
7print(lstripped)
8print(rstripped)
- This code demonstrates how to remove leading and trailing whitespace or whitespace from either side of a string in Python using
str.strip
,str.lstrip
, andstr.rstrip
.
Summary
By combining these operations, various string manipulations can be performed in Python.
You can follow along with the above article using Visual Studio Code on our YouTube channel. Please also check out the YouTube channel.