String Functions in Python: Explanation and Examples
String in python
- Concatenation: join two or more strings together using the "+" operator
- Repetition: repeat a string multiple times using the "*" operator
- Indexing: access individual characters of a string using square brackets [ ] and an index
- Slicing: extract a portion of a string using square brackets [start:end]
- Length: find the length of a string using the built-in "len()" function
- Formatting: insert values into a string using placeholders like "{}".
name = "John Doe"
greeting = "Hello, " + name + "!"
print(greeting)
Hello, John Doe!
repeat = name * 3
print(repeat)
John DoeJohn DoeJohn Doe
first_char = name[0]
print(first_char)
J
slice = name[1:4]
print(slice)
ohn
len_name = len(name)
print(len_name)
8
formatted = "My name is {} and I am {} years old.".format(name, 30)
print(formatted)
My name is John Doe and I am 30 years old.
Reverse String
In Python, you can reverse a string by using slicing with a step of -1. Here's an example:
original_string = "Hello, World!" reversed_string = original_string[::-1] print(reversed_string) "!dlroW ,olleH"
You can also use the reversed() function along with the join() method to reverse a string:
original_string = "Hello, World!"
reversed_string = "".join(reversed(original_string))
print(reversed_string)
"!dlroW ,olleH"
String find function
The find() method in Python is used to search for a substring within a larger string and returns the index of the first occurrence of the substring. If the substring is not found, it returns -1. Here's an example:
original_string = "Hello, World!"
index = original_string.find("World")
print(index)
7
You can also use the reversed() function along with the join() method to reverse a string:
original_string = "Hello, World! Hello, World!"
index = original_string.find("World", 8, 16)
print(index)
13
string count function
The count() method in Python is used to count the number of occurrences of a substring within a larger string. Here's an example:
original_string = "Hello, World! Hello, World!"
count = original_string.count("Hello")
print(count)
2
You can also specify the start and end indexes to limit the search area:
original_string = "Hello, World! Hello, World!" count = original_string.count("Hello", 0, 15) print(count) 1
string split function
The split() method in Python is used to split a string into a list of substrings based on a specified delimiter. By default, the delimiter is any whitespace character (space, tab, newline, etc.). Here's an example:
original_string = "Hello, World!"
substrings = original_string.split()
print(substrings)
['Hello,', 'World!']
You can also specify a different delimiter:
original_string = "Hello, World!"
substrings = original_string.split(",")
print(substrings)
['Hello', ' World!']
string partition function
original_string = "Hello, World!"
result = original_string.partition(",")
print(result)
('Hello', ',', ' World!')
In the example above, result[0] is "Hello", result[1] is ",", and result[2] is " World!".
string upper, lower, swapcase and title functions in python
In Python, the following string methods can be used to convert the case of a string:
- upper(): returns a new string with all the characters in uppercase
- lower(): returns a new string with all the characters in lowercase
- swapcase(): returns a new string with all uppercase characters converted to lowercase and vice versa
- title(): returns a new string with the first letter of each word capitalized
Here's an example of using these methods:
original_string = "Hello, World!"
upper_string = original_string.upper()
lower_string = original_string.lower()
swap_string = original_string.swapcase()
title_string = original_string.title()
print(upper_string)
HELLO, WORLD!
print(lower_string)
hello, world!
print(swap_string)
hELLO, wORLD!
print(title_string)
Hello, World!
difference between split and partition
The split() and partition() methods in Python are both used to split a string into parts, but they do so in different ways.
split() splits a string into a list of substrings based on a specified delimiter. By default, the delimiter is any whitespace character (space, tab, newline, etc.). The method returns a list of substrings, with the delimiter removed. Here's an example:
original_string = "Hello, World!"
substrings = original_string.split(",")
print(substrings)
['Hello', ' World!']
partition(), on the other hand, splits a string into a tuple containing three elements: the part before the specified delimiter, the delimiter itself, and the part after the delimiter. If the delimiter is not found, the method returns a tuple containing the original string and two empty strings. Here's an example:
original_string = "Hello, World!"
result = original_string.partition(",")
print(result)
('Hello', ',', ' World!')
difference between count and len
The count() and len() methods in Python are both used to get information about a string, but they return different values.
count() returns the number of occurrences of a specified substring within the string. Here's an example:
original_string = "Hello, World! Hello, World!"
count = original_string.count("Hello")
print(count)
2
len() returns the number of characters in the string, including spaces, punctuation, and special characters. Here's an example:
original_string = "Hello, World!"
length = len(original_string)
print(length)
13
So, in summary, count() returns the number of times a substring appears in a string, while len() returns the number of characters in a string.
some common string functions, along with their syntax, return type, and usage:
Function | Syntax | Return Type | Usage |
---|---|---|---|
len | len(string) | int | Returns the length of the given string. |
upper | string.upper() | str | Returns a new string with all characters in uppercase. |
lower | string.lower() | str | Returns a new string with all characters in lowercase. |
capitalize | string.capitalize() | str | Returns a new string with the first character capitalized. |
title | string.title() | str | Returns a new string with the first character of each word capitalized. |
isalpha | string.isalpha() | bool | Returns True if all characters in the string are alphabetic (a-z or A-Z). |
isnumeric | string.isnumeric() | bool | Returns True if all characters in the string are numeric. |
isalnum | string.isalnum() | bool | Returns True if all characters in the string are alphanumeric (a-z, A-Z, or 0-9). |
isspace | string.isspace() | bool | Returns True if all characters in the string are whitespace (spaces, tabs, newlines, etc.). |
strip | string.strip([chars]) | str | Returns a new string with leading and trailing whitespace removed. If the optional chars argument is provided, it specifies a set of characters to remove from the beginning and end of the string. |
split | string.split([sep[, maxsplit]]) | list | Returns a list of the words in the string, using sep as the delimiter. If maxsplit is given, at most maxsplit splits are done (i.e., the resulting list will have at most maxsplit+1 elements). |
join | sep.join(iterable) | str | Returns a string that is the concatenation of the strings in the iterable, separated by the sep string. |
replace | string.replace(old, new[, count]) | str | Returns a new string with all occurrences of old replaced with new. If count is given, only the first count occurrences are replaced. |
find | string.find(sub[, start[, end]]) | int | Returns the lowest index in the string where sub is found, or -1 if it is not found. If start and end are given, the search is limited to the specified slice of the string. |
rfind | string.rfind(sub[, start[, end]]) | int | Returns the highest index in the string where sub is found, or -1 if it is not found. If start and end are given, the search is limited to the specified slice of the string. |
count | string.count(sub[, start[, end]]) | int | Returns the number of non-overlapping occurrences of sub in the string. If start and end are given, the search is limited to the specified slice of the string. |
startswith | string.startswith(prefix[, start[, end]]) | bool | Returns True if the string starts with prefix, False otherwise. If start and end are |