String Manipulations
Python offers a rich set of built-in functions and methods for manipulating strings. Here's a breakdown of common techniques:
Basic Operations
·
Concatenation: Combining strings using the
+
operator.
Python
first_name =
"John"
last_name =
"Doe"
full_name = first_name +
" " + last_name
· Slicing: Extracting substrings using indices.
Python
text =
"Hello, World!"
substring = text[
7:
12]
# Output: "World"
·
Length: Determining the length of a string using len()
.
Python
text =
"Python"
length =
len(text)
# Output: 6
Case Conversion
·
lower()
: Converts all characters to
lowercase.
·
upper()
: Converts all characters to
uppercase.
·
title()
: Capitalizes the first
letter of each word.
·
capitalize()
: Capitalizes the first
character of the string.
·
swapcase()
: Swaps cases of all
characters.
Searching and Replacing
·
find()
: Returns the index of the
first occurrence of a substring.
·
rfind()
: Returns the index of the
last occurrence of a substring.
·
index()
: Similar to find()
, but raises a ValueError
if not found.
·
rindex()
: Similar to rfind()
, but raises a ValueError
if not found.
·
replace()
: Replaces occurrences of a
substring with another.
Stripping Characters
·
strip()
: Removes leading and
trailing whitespace.
·
lstrip()
: Removes leading
whitespace.
·
rstrip()
: Removes trailing
whitespace.
Splitting and Joining
·
split()
: Splits a string into a
list of substrings based on a delimiter.
·
join()
: Joins elements of an
iterable into a string using a separator.
Other Useful Methods
·
count()
: Counts the occurrences of
a substring.
· startswith(): Checks if the string starts with a specified substring.
· endswith(): Checks if the string ends with a specified substring.
·
isalnum()
: Checks if all characters
are alphanumeric.
·
isalpha()
: Checks if all characters
are alphabetic.
·
isdigit()
: Checks if all characters
are digits.
·
isspace()
: Checks if all characters
are whitespace.
Example
Python
text =
" This is a sample string "
words = text.strip().split()
new_text =
"-".join(words)
print(new_text)
# Output: This-is-a-sample-string
By combining these methods, you can perform complex string manipulations to suit your needs.