0% found this document useful (0 votes)
13 views20 pages

1.9 String Functions

The document provides an overview of various built-in string functions in Python, including methods for determining string length, converting case, stripping whitespace, checking prefixes and suffixes, replacing substrings, splitting and joining strings, and validating character types. Each function is explained with examples demonstrating its usage and output. These string functions are essential for manipulating and processing text data in Python.

Uploaded by

Bhargav Rajyagor
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views20 pages

1.9 String Functions

The document provides an overview of various built-in string functions in Python, including methods for determining string length, converting case, stripping whitespace, checking prefixes and suffixes, replacing substrings, splitting and joining strings, and validating character types. Each function is explained with examples demonstrating its usage and output. These string functions are essential for manipulating and processing text data in Python.

Uploaded by

Bhargav Rajyagor
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 20

Unit – 1

Introduction to Python
1.9 String Functions
Python String Function : len(string)
len(string) is a built-in function used to determine the length (number of characters) of a given string. It returns an
integer representing the number of characters in the string, including whitespace characters.
# Example strings
string1 = "Hello, World!"
string2 = "Python is amazing"
string3 = ""

# Calculate the length of the strings


length1 = len(string1)
length2 = len(string2)
length3 = len(string3)

# Output the results


print(length1) # Output: 13 (including spaces and punctuation)
print(length2) # Output: 17 (including spaces)
print(length3) # Output: 0 (an empty string has length 0)
2
Python String Function : string.lower()
string.lower() is a built-in string method used to convert all characters in a string to lowercase. It returns a new string
with all alphabetic characters in lowercase while leaving non-alphabetic characters unchanged.
# Example string
text = "PyThOn iS aMaZiNg!"

# Convert the string to lowercase


lowercase_text = text.lower()

# Output the result


print(lowercase_text) # Output: "python is amazing!"

In this example, the lower() method is called on the string text. It converts all the uppercase characters (P, T, O, N, S, A,
M, Z, I, and G) to their lowercase counterparts, resulting in the new string "python is amazing!".

It's important to note that the lower() method does not modify the original string; instead, it creates a new string with
the desired transformation. If you want to work with the lowercase version of a string, you should store the result in a
new variable, as shown in the example above.
3
Python String Function : string.upper()
string.upper() is a built-in string method used to convert all characters in a string to uppercase. It returns a new string
with all alphabetic characters in uppercase while leaving non-alphabetic characters unchanged.
# Example string
text = "PyThOn iS aMaZiNg!"

# Convert the string to uppercase


uppercase_text = text.upper()

# Output the result


print(uppercase_text) # Output: "PYTHON IS AMAZING!"

In this example, the upper() method is called on the string text. It converts all the lowercase characters (y, h, o, n, i, s, a,
m, z, i, n, g) to their uppercase counterparts, resulting in the new string "PYTHON IS AMAZING!".

As with string.lower(), the upper() method does not modify the original string but instead creates a new string with the
desired transformation.

4
Python String Function : string.capitalize()
string.capitalize() is a built-in string method used to capitalize the first character of a string while converting all other
characters to lowercase. It returns a new string with the modified capitalization.
# Example string
text = "python is amazing!"

# Capitalize the first character


capitalized_text = text.capitalize()

# Output the result


print(capitalized_text) # Output: "Python is amazing!"

In this example, the capitalize() method is called on the string text. It capitalizes the first character 'p' and converts all
other characters in the string to lowercase. The resulting new string is "Python is amazing!".

It's important to note that string.capitalize() only capitalizes the first character of the entire string. If you have multiple
words in the string and want to capitalize the first character of each word, you should use the string.title() method
instead.
5
Python String Function : string.title()
string.title() is a built-in string method used to capitalize the first character of each word in a string. It returns a new
string with the modified capitalization.
# Example string
text = "python is amazing!"

# Capitalize the first character of each word


title_text = text.title()

# Output the result


print(title_text) # Output: "Python Is Amazing!"

In this example, the title() method is called on the string text. It capitalizes the first character of each word ("python",
"is", "amazing") in the string and converts all other characters to lowercase. The resulting new string is "Python Is
Amazing!".

6
Python String Function : string.strip()
string.strip() is a built-in string method used to remove leading and trailing whitespace characters from a string. It returns a new
string with the whitespace characters removed.
# Example string with leading and trailing whitespace
text = " Hello, World! "

# Remove leading and trailing whitespace


stripped_text = text.strip()

# Output the result


print(stripped_text) # Output: "Hello, World!"

In this example, the strip() method is called on the string text. It removes the leading spaces at the beginning and the trailing
spaces at the end of the string, resulting in the new string "Hello, World!".

The string.strip() method is particularly useful when dealing with user input or reading data from files, where leading and trailing
whitespace might be unintentionally present.

If you only want to remove leading whitespace (spaces at the beginning of the string) or trailing whitespace (spaces at the end
of the string), you can use the methods string.lstrip() and string.rstrip() respectively. These methods also return new strings with
7
the specified whitespace removed.
Python String Function : string.startswith(prefix)
string.startswith(prefix) is a built-in string method used to check whether a string starts with a specific prefix. It returns a
Boolean value: True if the string starts with the specified prefix and False otherwise.
# Example string
text = "Hello, World!"

# Check if the string starts with the prefix


starts_with_hello = text.startswith("Hello")
starts_with_hi = text.startswith("Hi")
In this example, the startswith() method is called on the string text. It checks whether
the string starts with the prefixes "Hello" and "Hi". The result is True for "Hello" because
# Output the results
the string does start with this prefix, and False for "Hi" because the string does not start
print(starts_with_hello) # Output: True
with this prefix.
print(starts_with_hi) # Output: False

The string.startswith() method is helpful when you need to check if a string has a
specific prefix before performing certain operations or logic based on the initial
characters of the string.

8
Python String Function : string.endswith(suffix)
string.endswith(suffix) is a built-in string method used to check whether a string ends with a specific suffix. It returns a Boolean
value: True if the string ends with the specified suffix and False otherwise.
# Example string
text = "Hello, World!"

# Check if the string ends with the suffix


ends_with_world = text.endswith("World!")
ends_with_universe = text.endswith("Universe!")
In this example, the endswith() method is called on the string text. It checks whether
the string ends with the suffixes "World!" and "Universe!". The result is True for "World!"
# Output the results
because the string does end with this suffix, and False for "Universe!" because the
print(ends_with_world) # Output: True
string does not end with this suffix.
print(ends_with_universe) # Output: False

The string.endswith() method is useful when you need to check if a string has a specific
suffix before performing certain operations or logic based on the ending characters of
the string.

9
Python String Function : string.replace(old, new)
string.replace(old, new) is a built-in string method used to replace all occurrences of a substring (referred to as "old") with
another substring (referred to as "new") in a given string. It returns a new string with the replacements made.
# Example string
text = "Hello, World! Hello, Universe!"

# Replace "Hello" with "Hi"


new_text = text.replace("Hello", "Hi")

# Output the result


print(new_text) # Output: "Hi, World! Hi, Universe!"

In this example, the replace() method is called on the string text. It replaces all
occurrences of the substring "Hello" with the substring "Hi". The resulting new string is
"Hi, World! Hi, Universe!".

10
Python String Function : string.replace(old, new)
It's important to note that the replace() method does not modify the original string but instead creates a new string with the
replacements. If you want to perform replacements in place (modify the original string), you can assign the result back to the
original variable, like this:
# Modify the original string with replacements
text = "Hello, World! Hello, Universe!"
text = text.replace("Hello", "Hi")

print(text) # Output: "Hi, World! Hi, Universe!"

By reassigning the result of text.replace() back to the text variable, we update the
content of the original string.

11
Python String Function : string.split()
string.split() is a built-in string method used to split a string into a list of substrings based on a specified separator. By default, if
no separator is provided, it will split the string based on whitespace characters (spaces, tabs, and newlines).
# Example string
text = "Hello, World! How are you?"

# Split the string using the default separator (whitespace)


words = text.split()

# Output the result


print(words) # Output: ['Hello,', 'World!', 'How', 'are', 'you?']

In this example, the split() method is called on the string text without providing any
separator explicitly. As a result, the string is split into substrings using the default
separator (whitespace). The resulting list words contains each word from the original
string as separate elements.

12
Python String Function : string.split()
You can also specify a custom separator to split the string. For example:
# Split the string using a comma (',') as the separator
items = "apple, orange, banana".split(",")

# Output the result


print(items) # Output: ['apple', ' orange', ' banana']

In this case, the split(",") method splits the string "apple, orange, banana" using the
comma (,) as the separator, resulting in a list of items ['apple', ' orange', ' banana'].

The split() method is useful when you want to break down a string into smaller parts or
separate words or values based on a specific pattern or delimiter.

13
Python String Function : string.join(iterable)
String.join(iterable) is a built-in string method used to concatenate elements of an iterable (e.g., a list or tuple) into a single
string. The method takes an iterable as an argument and returns a new string where the elements of the iterable are joined
together using the original string as the separator.
# Example list of strings
words = ["Hello", "World", "How", "are", "you?"]

# Join the list elements into a single string using a space as the separator
sentence = " ".join(words)

# Output the result


print(sentence) # Output: "Hello World How are you?"

In this example, the join() method is called on the string " ". It takes the list of strings
words as an argument and joins the elements of the list into a single string, separated
by a space (" "). The resulting new string is "Hello World How are you?".

14
Python String Function : string.join(iterable)
You can use any string as the separator in string.join(iterable)
# Join the list elements into a single string using a comma as the separator
csv_string = ",".join(["apple", "orange", "banana"])

# Output the result


print(csv_string) # Output: "apple,orange,banana"

In this case, the join(",") method joins the list elements "apple", "orange", and "banana"
into a single string with commas as the separator, resulting in "apple,orange,banana".

The join() method is a convenient way to create strings from the elements of an iterable
and is widely used in various data processing and text manipulation tasks.

15
Python String Function : string.isdigit()
string.isdigit() is a built-in string method used to check if all the characters in a string are digits (numeric characters). It returns a
Boolean value: True if all characters are digits, and False otherwise.

# Example strings
In this example, the isdigit() method is called on three different strings: "12345",
string1 = "12345"
string2 = "Hello123" "Hello123", and "42.5". The result is True for the first string ("12345") because all
string3 = "42.5" characters in that string are digits. For the other two strings, is_digit2 and is_digit3, the
result is False because they contain non-digit characters, such as letters and a decimal
# Check if the strings consist of digits
is_digit1 = string1.isdigit() point.
is_digit2 = string2.isdigit()
is_digit3 = string3.isdigit()
The string.isdigit() method is helpful when you need to check if a string represents a
# Output the results valid integer value before performing operations that require numeric input. It is
print(is_digit1) # Output: True essential to ensure that the entire string consists of numeric characters to get an
print(is_digit2) # Output: False
accurate result from this method.
print(is_digit3) # Output: False

16
Python String Function : string.isalpha()
string.isalpha() is a built-in string method used to check if all the characters in a string are alphabetic characters (letters). It
returns a Boolean value: True if all characters are letters, and False otherwise.

# Example strings
string1 = "Hello"
string2 = "Hello123"
string3 = "12345"

# Check if the strings consist of alphabetic characters


is_alpha1 = string1.isalpha()
is_alpha2 = string2.isalpha() In this example, the isalpha() method is called on three different strings: "Hello",
is_alpha3 = string3.isalpha()
"Hello123", and "12345". The result is True for the first string ("Hello") because all
# Output the results characters in that string are letters. For the other two strings, is_alpha2 and is_alpha3,
print(is_alpha1) # Output: True the result is False because they contain non-letter characters, such as digits.
print(is_alpha2) # Output: False
print(is_alpha3) # Output: False
The string.isalpha() method is useful when you need to check if a string consists only of
letters, without any digits or other non-alphabetic characters. It can be used as a
validation check when working with textual data or user input.

17
Python String Function : string.islower()
string.islower() is a built-in string method used to check if all the characters in a string are lowercase alphabetic characters
(lowercase letters). It returns a Boolean value: True if all characters are lowercase letters, and False otherwise.

# Example strings
string1 = "hello"
string2 = "Hello"
string3 = "12345"

# Check if the strings consist of lowercase alphabetic characters


is_lower1 = string1.islower()
is_lower2 = string2.islower() In this example, the islower() method is called on three different strings: "hello", "Hello",
is_lower3 = string3.islower()
and "12345". The result is True for the first string ("hello") because all characters in that
# Output the results string are lowercase letters. For the other two strings, is_lower2 and is_lower3, the
print(is_lower1) # Output: True result is False because they either contain uppercase letters or non-letter characters
print(is_lower2) # Output: False
(digits in this case).
print(is_lower3) # Output: False

The string.islower() method is useful when you want to check if a string is entirely
composed of lowercase letters, which can be helpful for data validation or when
performing specific text processing tasks that require lowercase input.
18
Python String Function : string.isupper()
string.isupper() is a built-in string method used to check if all the characters in a string are uppercase alphabetic characters
(uppercase letters). It returns a Boolean value: True if all characters are uppercase letters, and False otherwise.

# Example strings
string1 = "HELLO"
string2 = "Hello"
string3 = "12345"

# Check if the strings consist of uppercase alphabetic characters


is_upper1 = string1.isupper()
is_upper2 = string2.isupper() In this example, the isupper() method is called on three different strings: "HELLO",
is_upper3 = string3.isupper()
"Hello", and "12345". The result is True for the first string ("HELLO") because all
# Output the results characters in that string are uppercase letters. For the other two strings, is_upper2 and
print(is_upper1) # Output: True is_upper3, the result is False because they either contain lowercase letters or non-
print(is_upper2) # Output: False
letter characters (digits in this case).
print(is_upper3) # Output: False

The string.isupper() method is useful when you want to check if a string is entirely
composed of uppercase letters, which can be helpful for data validation or when
performing specific text processing tasks that require uppercase input.
19
Thanks

You might also like