0% found this document useful (0 votes)
5 views6 pages

String Notes

Chapter 2 discusses the string data type in Python, highlighting its characteristics such as immutability, creation methods, and indexing. It covers string operations like concatenation, replication, and built-in functions, as well as string formatting techniques including f-strings, the str.format() method, and the modulo operator. The chapter provides examples for each concept to illustrate their usage.

Uploaded by

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

String Notes

Chapter 2 discusses the string data type in Python, highlighting its characteristics such as immutability, creation methods, and indexing. It covers string operations like concatenation, replication, and built-in functions, as well as string formatting techniques including f-strings, the str.format() method, and the modulo operator. The chapter provides examples for each concept to illustrate their usage.

Uploaded by

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

Chapter – 2

String - Data Types


In Python, the string data type, represented as str, is used to store sequences of characters, essentially textual
data.

Key characteristics of Python strings:


• Sequence of Characters:
Strings are ordered collections of characters, including letters, numbers, symbols, and spaces.

• Immutability:
➢ Strings in Python are immutable, meaning that once a string is created, its content cannot be directly
changed.
➢ Any operation that appears to modify a string, like concatenation or replacement, actually creates a
new string object in memory.
➢ For example:
my_string = "Hello"
my_string = my_string + " World" # Creates a new string "Hello World"
print(my_string)
# Attempting to change a character will result in an error:
my_string[0] = 'h' # TypeError

• Creation:
➢ You can create a string by enclosing the characters in either single quotes (' ') or double quotes (" ").
➢ For multi-line strings or to include both single and double quotes within a string without escaping,
you can use triple quotes (' ' ' ' ' ' or " " " " " ").
➢ For example:
my_string = "Hello, World!" # Double quotes
another_string = 'Python is fun.' # Single quotes
multi_line_string = """This is a string
that spans multiple lines.""" # Triple quotes

• No Character Data Type:


Python does not have a separate character data type; a single character is simply a string of length one.

• Raw strings
➢ Raw strings are prefixed with r or R and treat backslashes (\) as literal characters, disabling escape
sequence interpretation.
➢ This is particularly useful when working with regular expressions or file paths that contain many
backslashes.
➢ For example:
path = r"C:\Users\Documents\file.txt"
print(path)
# Output: C:\Users\Documents\file.txt

• Indexing and Slicing:


Individual characters or substrings can be accessed using indexing (e.g., my_string[0]) and slicing
(e.g., my_string[0:5]).
Python supports both positive (from the beginning, starting at 0) and negative (from the end, starting at -
1) indexing.
➢ Strings are sequences, so you can access individual characters using indexing.
o Indices start at 0 for the first character, and you can also use negative indices to count from
the end of the string (-1 for the last character, -2 for the second-to-last, etc.).
o Note: Accessing an index out of range will cause an IndexError. Only integers are allowed as
indices and using a float or other types will result in a TypeError.
➢ Slicing allows you to extract a portion (substring) of a string using the syntax string[start:end:step].
o start is the inclusive starting index.
o end is the exclusive ending index.
o step is an optional argument that specifies the interval between characters (default is 1).
➢ For example:
my_string = "Python is a programing language"
print(my_string[0]) # Output: P
print(my_string[1:4]) # Output: yth
print(my_string[::]) # Output: Python is a programing language
print(my_string[:5]) # Output: Pytho
print(my_string[3:]) # Output: hon is a programing language
print(my_string[::-1]) # Output: egaugnal gnimargorp a si nohtyP
print(my_string[8:1:-1]) # Output: si noht
print(my_string[-9:8]) # Output:
print(my_string[-9:-2]) # Output:languaOperations:

String Concatenation (+)


String concatenation in Python refers to the process of combining two or more strings into a single, longer
string. Python offers several methods for achieving this:
• Using the + Operator: This is the most straightforward and commonly used method for
concatenating a few strings.
string1 = "Hello"
string2 = "World"
result = string1 + " " + string2
print(result) # Output: Hello World
• Using the += Operator (Augmented Assignment): This operator appends a string to an existing
string, modifying the original string in place (though technically, a new string object is created and
assigned back to the variable).
message = "Good"
message += " morning"
print(message) # Output: Good morning
• Using the .join() Method: This method is highly efficient for concatenating a large number of
strings, especially when they are stored in an iterable like a list or tuple. It takes an iterable of strings
as an argument and joins them using the string on which the method is called as a separator.
words = ["Python", "is", "fun"]
sentence = " ".join(words)
print(sentence) # Output: Python is fun
empty_separator = "".join(["No", "Spaces"])
print(empty_separator) # Output: NoSpaces
Note: String can be concatenated with string only i.e. both side of + operator should be string.
String Replication (*)
In Python, string repetition, also known as string replication, is achieved using the multiplication operator
(*). This operator allows for the creation of a new string by repeating an existing string a specified number
of times.
Basic Syntax: repeated_string = original_string * integer_value
where:
• original_string is the string to be repeated.
• integer_value is the number of times the string should be repeated. This must be a non-negative
integer. If integer_value is 0, an empty string "" is returned.
Example:
text = "Python "
repeated_text = text * 3
print(repeated_text)
Output: Python Python Python
String Built In Functions:
Function Description Example Output
len() Returns the length of the str1 = 'Hello World!' 12
given string print( len(str1) )
title() Returns the string with first letter of str1 = 'hello WORLD!' 'Hello World!'
every word in the string in uppercase print( str1.title() )
and rest in lowercase
lower() Returns the string with all uppercase str1 = 'hello WORLD!' 'hello world!'
letters converted to lowercase print( str1.lower() )
upper() Returns the string with all str1 = 'hello WORLD!' HELLO WORLD!
lowercase letters converted print ( str1.upper() ) HELLO 1234
to uppercase str1 = 'HELlo 1234'
print ( str1.upper() )
Capitalize() The capitalize() method in Python is a text1 = "hello world" Hello world
built-in string method used to modify the print(text1.capitalize()) 123 example
case of characters within a string. It text3 = "123 example"
specifically converts the first character of cap = text3.capitalize()
the string to uppercase and all subsequent print(cap)
characters to
lowercase. The capitalize() method does
not accept any parameters. It is called
directly on the string object.
istitle() Returns True if the string is non- str1 = 'Hello World!' True
empty and title case, i.e., the first print ( str1.istitle() ) False
letter of every word in the string in str1 = 'hello World!'
uppercase and rest in lowercase print ( str1.istitle() )
islower() Returns True if the string is tr1 = 'hello world!' True
non-empty and has all print ( str1.islower() ) True
lowercase alphabets, or has str1 = 'hello 1234' True
at least one character as print ( str1.islower() ) False
lowercase alphabet and rest str1 = 'hello ??' False
are non-alphabet characters print ( str1.islower() )
str1 = '1234'
print ( str1.islower() )
str1 = 'Hello World!'
print ( str1.islower() )
isupper() Returns True if the string is str1 = 'HELLO WORLD!' True
non-empty and has all print ( str1.isupper() ) True
uppercase alphabets, or has str1 = 'HELLO 1234' True
at least one character as print ( str1.isupper() ) False
uppercase character and rest str1 = 'HELLO ??' False
are non-alphabet characters print ( str1.isupper() )
str1 = '1234'
print ( str1.isupper() )
str1 = 'Hello World!'
print ( str1.isupper() )
isalnum() Returns True if characters of str1 = 'HelloWorld' True
the given string are either print ( str1.isalnum() ) True
alphabets or numeric. If str1 = 'HelloWorld2' False
whitespace or special print ( str1.isalnum() )
symbols are part of the given str1 = 'HelloWorld!!'
string or the string is empty it print ( str1.isalnum() )
returns False
isspace() Returns True if the string is str1=' \n \t \r' True
non-empty and all characters print (str1.isspace() ) False
are white spaces (blank, tab, str1 = 'Hello \n'
newline, carriage return) print ( str1.isspace() )
isdigit() Returns True if the string is tr1 = '1234 ' False
having only 0 to 9 digits. print ( str1.isdigit() ) False
str1 = '1234.98' False
print ( str1.isdigit() ) True
str1 = 'hello ??'
print ( str1.isdigit() )
str1 = '1234'
print ( str1.isdigit ()
count() 'HELLO WORLD!' count(str, start, end) str1 = 'Hello World! Hello Hello' 2
Returns number of times substring str print(str1.count('Hello',12,25)) 3
occurs in the given string. If we do not print ( str1.count('Hello') )
give start index and end index then
searching starts from index 0 and ends at
length of the string
find(str,start, Returns the first occurrence of index of str1 = 'Hello World! Hello Hello' 13
end) substring str occurring in the given string. print ( str1.find('Hello',10,20) ) 19
If we do not give start and end then print( str1.find('Hello',15,25) ) 0
searching starts from index 0 and ends at print ( str1.find('Hello') ) -1
length of the string. If the substring is not print ( str1.find('Hee') )
present in the given string, then the
function returns -1
index(str, Same as find() but raises an str1 = 'Hello World! Hello Hello' 0
start, end) exception if the substring is print ( str1.index('Hello') ) ValueError:
not present in the given string print ( str1.index('Hee') ) substring not
found
endswith() Returns True if the given str1 = 'Hello World!' True
string ends with the supplied print ( str1.endswith('World!') ) True
substring otherwise returns print ( str1.endswith('!') ) False
False print ( str1.endswith('lde') )
startswith() Returns True if the given string starts str1 = 'Hello World!' True
with the supplied substring otherwise print ( str1.startswith('He') ) False
returns False print ( str1.startswith('Hee') )
lstrip() False lstrip() Returns the string after str1 = ' Hello World! ' Hello World!
removing the spaces only on the left print ( str1.lstrip() )
of the string
rstrip() Returns the string after str1 = ' Hello World! ' Hello World!
removing the spaces only on print ( str1.rstrip() ) 21
the right of the string print(len(str1)) 17
str1= str1.rstrip()
print(len(str1))
strip() Returns the string after str1 = ' Hello World! ' Hello World!
removing the spaces both on print ( str1.strip() ) 21
the left and the right of the print(len(str1)) 12
string str1= str1.strip()
print(len(str1))
replace(oldstr, Replaces all occurrences of str1 = 'Hello World!' Hell* W*rld!
newstr) old string with the new string print ( str1.replace('o','*') ) Hello Country!
str1 = 'Hello World!' Bye World! Bye
print( str1.replace('World','Country'))
str1 = 'Hello World! Hello'
print ( str1.replace('Hello','Bye'))
join() Returns a string in which the str1 = ('HelloWorld!') H-e-l-l-o-W-o-r-l-d-!
characters in the string have str2 = '-' #separator
been joined by a separator print ( str2.join(str1) )
partition()) Partitions the given string at the first str1 = 'I love India' ('I love India', '', '')
occurrence of the substring print (str1.partition('is')) ('I love India', '', '')
(separator) and returns the string print (str1.partition('are'))
partitioned into three parts. 1.
Substring before the separator 2.
Separator 3. Substring after the
separator If the separator is not found
in the string, it returns the whole
string itself and two empty strings
split() Returns a list of words str1 = 'I love India' ['I', 'love', 'India']
delimited by the specified print (str1.split()) ['I love Indi', '']
substring. If no delimiter is print ( str1.split('a'))
given then words are
separated by space.

• String formatting
String formatting in Python is a crucial skill for crafting dynamic and readable text output. It involves
embedding variables, expressions, and custom formatting into strings. Python provides several methods to
achieve this, each with unique advantages and use cases:
1. F-strings (formatted string literals)
➢ Introduced in Python 3.6, f-strings are the modern, recommended approach for string formatting due
to their conciseness, readability, and performance.
➢ To create an f-string, prefix the string literal with 'f' or 'F'. Variables and expressions are enclosed in
curly braces {} within the string.
Example:
name = "Jennifer"
age = 23
message = f"My name is {name} and I am {age} years old."
print(message)
Output: My name is Jennifer and I am 23 years old.
name = "Alice"
age = 30
print(f"My name is {name} and I am {age} years old.")
# Output: My name is Alice and I am 30 years old.

2. str.format() method
➢ Introduced in Python 2.6 and backported to Python 2.7, this method is a versatile alternative to older
formatting techniques.
➢ It utilizes placeholders {} in the string that are filled by calling the format () method with arguments.
➢ Arguments can be passed positionally or using keyword arguments, allowing for reordering and
clarity.
➢ Example:
txt = "My name is John, I am {age}."
print(txt.format(age=36))
Output: My name is John, I am 36.
3. Modulo (%) operator
➢ This is the oldest method of string formatting, similar to the printf() function in C.
➢ It uses % as a placeholder for variables and conversion specifiers (e.g., %s for string, %d for integer
and %f for floating point numbers).
➢ While still functional, it's generally considered less readable and flexible compared to f-strings and
the str.format() method, especially when dealing with numerous variables.
➢ Example:
name = "Mohan"
age = 5
print("My name is %s and I am %d years old" % (name, age))
Output: My name is Mohan and I am 5 years old
# This prints out "Hello, John!" # This prints out: A list: [1, 2, 3]
name = "John" mylist = [1,2,3]
print("Hello, %s!" % name) print("A list: %s" % mylist)
data = ("John", "Doe", 53.44)
format_string = "Hello %s %s. Your current balance is $%s."
print(format_string % data)4. String template class
Which method should you choose?
• For new projects and Python 3.6+, f-strings are generally the preferred method due to their
readability, conciseness, and performance.
• The str.format() method remains a viable option, particularly when working with Python versions
older than 3.6 or when a more flexible approach to template creation is needed.
• The modulo operator (%) is largely considered a legacy approach and is best used for maintaining
older code.
New Word
"Backporting" refers to the practice of taking software updates, particularly security patches or new
features, from a newer version of a software and applying them to an older, supported version. This is done
to address vulnerabilities, maintain functionality, or introduce new features in older systems without
requiring a complete upgrade.
Here's a more detailed explanation:
What it is: Backporting involves taking code changes from a newer software version and adapting them to
work with an older version. It's like taking a new feature from a more recent car model and installing it in
your older car, allowing you to benefit from the feature without buying a new car.

You might also like