0% found this document useful (0 votes)
25 views22 pages

Unit 4

The document provides an overview of string manipulation in Python, detailing string properties, operators, and functions. It explains how to access string elements, perform operations like concatenation and repetition, and utilize various string methods. Additionally, it covers string formatting, slicing, and built-in functions for effective string handling.
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)
25 views22 pages

Unit 4

The document provides an overview of string manipulation in Python, detailing string properties, operators, and functions. It explains how to access string elements, perform operations like concatenation and repetition, and utilize various string methods. Additionally, it covers string formatting, slicing, and built-in functions for effective string handling.
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/ 22

UNIT-4

String Manipulation
string-

String is a collection of alphabets, words or other characters. It is one of


the primitive data structures and are the building blocks for data
manipulation. Python has a built-in string class named str. Python
strings are "immutable" which means they cannot be changed after they
are created.
Accessing individual elements
Since strings are a sequence of characters, you can access it through slicing and indexing just
like you would with Python lists or tuples. Strings are indexed with respect to each character
in the string and the indexing begins at 0:
snack = "Chocolate cookie."
print(snack[0])
print(snack[9])
print(snack[-1])
print(snack[0:])
print(snack[:-1])
print(snack[:])
Python String Operators
Operator Description

•Assignment operator: “=”


•Concatenate operator: “+”
•String repetition operator: “*”
•String slicing operator: “[]”
•String comparison operator: “==” &
“!=”
•Membership operator: “in” & “not in”
•Escape sequence operator: “\”
•String formatting operator: “%” &
“{}”
1 – Assignment Operator “=”
Python string can be assigned to any variable with an assignment operator “= “.
Python string can be defined with either single quotes [”], double quotes[“”], or
triple quotes[‘””‘]. var_name = “string” assigns “string” to variable var_name.

Code:

string1 = "hello"
string2 = 'hello'
string3 = '''hello'''
print(string1)
print(string2)
print(string3)
2 – Concatenate Operator “+”
Two strings can be concatenated or joined using the “+” operator in Python, as explained in the below
example code:

Code:

string1 = "hello"
string2 = "world "
string_combined = string1+string2
print(string_combined)
Output:

hello world
3 – String Repetition Operator “*”
The same string can be repeated in Python by n times using string*n, as explained in the below example.

Code:

string1 = "helloworld "


print(string1*2)
print(string1*3)
print(string1*4)
print(string1*5)
#5 – String Comparison Operator “==” & “!=”
The string comparison operator in Python is used to compare two strings.

The “==” operator returns Boolean True if two strings are the same and Boolean False if two strings are different.
The “!=” operator returns Boolean True if two strings are not the same and returns Boolean False if two strings
are the same.
These operators are mainly used along with the if condition to compare two strings where the decision will be
taken based on string comparison.

Code:

string1 = "hello"
string2 = "hello, world"
string3 = "hello, world"
string4 = "world"
print(string1==string4)
print(string2==string3)
print(string1!=string4)
print(string2!=string3)
#6 – Membership Operator “in” & “not in”
The membership operator searches whether the specific character is part/member of a given input
Python string.

“a” in the string: Returns boolean True if “a” is in the string and returns False if “a” is not in the string.
“a” not in the string: Returns boolean True if “a” is not in the string and returns False if “a” is in the string.
A membership operator is also useful to find whether a specific substring is part of a given string.

Code:

string1 = "helloworld"
print("w" in string1)
print("W" in string1)
print("t" in string1)
print("t" not in string1)
print("hello" in string1)
print("Hello" in string1)
print("hello" not in string1)
#7 – Escape Sequence Operator “\”
An escape character is used to insert a non-allowed character in the given input string. An escape character is a
“\” or “backslash” operator followed by a non-allowed character. An example of a non-allowed character in a
Python string is inserting double quotes in the string surrounded by double quotes.

1. Example of non-allowed double quotes in Python string:

Code:

string = "Hello world I am from "India""


print(string)
Output:

String Operators in Python 1-7


2. Example of non-allowed double quotes with escape sequence operator:

Code:

string = "Hello world I am from \"India\""


print(string)
#8 – String Formatting Operator “%”
The string formatting operator is used to format a string as per requirement. To insert another type of
variable along with string, the “%” operator is used along with Python string. “%” is prefixed to another
character, indicating the type of value we want to insert along with the Python string. Please refer to the
table below for some of the commonly used different string formatting specifiers:

Operator Description

%d Signed decimal integer


%u unsigned decimal integer
%c Character
%s String
%f Floating-point real number
What Is Slicing?
Slicing is the extraction of a part of a string, list, or tuple. It enables users to access the specific range of elements
by mentioning their indices.

In Python, the [:] notation is used to slice a sequence (such as a string, tuple, or list).

Syntax: Object [start:stop:step]

“Start” specifies the starting index of a slice


“Stop” specifies the ending element of a slice
You can use one of these if you want to skip certain items
@
Number_string = "1020304050“
print(number_string[0:-1:2])

•s[1:4] is 'ell' -- chars starting at index 1 and


extending up to but not including index 4
•s[1:] is 'ello' -- omitting either index defaults to the
start or end of the string
•s[:] is 'Hello' -- omitting both always gives us a copy
of the whole thing.
Python String functions
Python provides various in-built functions that are used for
string handling. Those are

len()
lower()
upper()
replace()
join()
split()
find()
isalnum()
isdigit()
isnumeric()
islower()
isupper()
len(string): Returns the length of the string.

string.lower(): Converts all characters in the string to lowercase.

string.upper(): Converts all characters in the string to uppercase.

string.title(): Converts the first character of each word to uppercase.

string.strip(): Removes leading and trailing whitespaces from the string.

string.replace(old, new): Replaces all occurrences of the substring old with new in the string.

string.split(separator): Splits the string into a list of substrings based on the separator.

string.join(iterable): Joins the elements of an iterable (e.g., a list) into a single string using string as a separator.

string.find(substring): Returns the lowest index in the string where substring is found, or -1 if substring is not found.

string.startswith(prefix): Returns True if the string starts with the specified prefix; otherwise, returns False.

string.endswith(suffix): Returns True if the string ends with the specified suffix; otherwise, returns False.
isalnum():- Returns True if all characters in the string are alphanumeric.
isdigit():- Returns True if all characters in the string are digits.
isnumeric():- Returns True if all characters in the string are numeric.
String Method

string.capitalize(): Capitalizes the first character of the string.

Count()-The count() method returns the number of occurrences of a substring in the given string.

Casefold()-The casefold() method converts all characters of the string into lowercase letters and returns a new
string.

Index()-The index() method returns the index of a substring inside the string (if found). If the substring is not
found, it raises an exception.

The endswith() method returns True if the string ends with the specified value, otherwise False.

The startswith() method returns True if the string starts with the specified value, otherwise

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy