0% found this document useful (0 votes)
18 views32 pages

03 20240930 Strings Collections-Data-Types

The document provides an overview of basic elements of Python, focusing on strings and collections data types. It covers string creation, comparison, slicing, striding, operators, methods, and formatting, as well as introduces tuples, lists, sets, and dictionaries. The content is structured to facilitate understanding of string manipulation and collection handling in Python programming.

Uploaded by

scs623170
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)
18 views32 pages

03 20240930 Strings Collections-Data-Types

The document provides an overview of basic elements of Python, focusing on strings and collections data types. It covers string creation, comparison, slicing, striding, operators, methods, and formatting, as well as introduces tuples, lists, sets, and dictionaries. The content is structured to facilitate understanding of string manipulation and collection handling in Python programming.

Uploaded by

scs623170
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/ 32

Basic Elements of Python

Prof. Murali Krishna Gurram


Dept. of Geo-Engineering & RDT
Centre for remote Sensing, AUCE
Andhra University, Visakhapatnam – 530 003
Dt. 30/09/2024
Basic Elements of Python

a) Strings
• Strings
• Comparing strings
• Slicing and Striding strings
• String operators and Methods
• String formatting with 'str.format‘

b) Collections Data Types:


• Tuples
• Lists
• Sets
• Dictionaries
• Iterating and Copying collections
Strings in Python
Strings in Python
Strings:
 Strings are sequences of characters enclosed in quotes (single,
double, or triple).

Unicode Representation:
 Python strings are Unicode-based, supporting a wide range of
characters from various languages and scripts.

Immutability:
 Strings are immutable, meaning their content cannot be
changed once created. New strings must be created to modify
existing ones.
Strings in Python
Strings:
Example Creating Strings:
my_string = "Hello, world!"
another_string = 'This is a string.'
multi_line_string = """This is a multi-line string.
It can span multiple lines.""“

print(my_string) print(another_string)
print(multi_line_string)

Output:
Hello World
This is a string.
This is a multi-line string.
It can span multiple lines..
Strings in Python
Strings:

Figure: Visualization of how characters in a string are stored in memory as an


indexed sequence.
Strings in Python
2. String Comparison:
 You can compare strings in Python using comparison operators (==, !=, <, >,
etc.).

 Comparisons are case-sensitive and based on lexicographical order (ASCII


values).

 Lexicographic Ordering: Strings are compared based on their Unicode code


points.

 For example, "apple" comes before "banana" in lexicographic order.

Example of string comparison:


print('apple' == 'apple') # True
print('apple' != 'Apple') # True
print('apple' < 'banana') # True (because 'a' comes before 'b')
Strings in Python
2. String Comparison:
 Equality: Use == to check if two strings are equal.
Example of string comparison:
if "Hello" == "hello":
print("Strings are equal.")
else:
print("Strings are not equal.")
Strings in Python
2. String Comparison:
 Inequality: Use != to check if two strings are not equal.

 Case Sensitivity: String comparisons are case-sensitive.

Example of string comparison:


"Hello" != "hello" # True
Strings in Python
3. Slicing and Striding Strings:
 String Slicing: Slicing is used to extract a part of a string by
specifying a range of indices.
 Syntax: string[start:end]
 start: starting index (inclusive)
 end: stopping index (exclusive)

Example :
text = "Python"
print(text[0:3]) # Output: Pyt
print(text[:4]) # Output: Pyth
print(text[2:]) # Output: thon
Strings in Python
3. Slicing and Striding Strings:
String Slicing:
Example :
text = "Geoinformatics"
print(text[:4]) # Output: Geo
print(text[-4:]) # Output: tics
print(text[2:8]) # Output: oinfo
Strings in Python
3. Slicing and Striding Strings:
String Slicing: Extract a substring using square brackets and
indices.

Example :
my_string = "Python is awesome!"
substring = my_string[7:14]
Output:
"is awesome"
Strings in Python
3. Slicing and Striding Strings:
 String Striding: Striding allows you to step over elements within
a slice.
 Syntax: string[start:end:step]
 step: controls how much to increment between each
character
Example :
print(text[::2]) # Output: Pto (every 2nd character)
print(text[::-1]) # Output: nohtyP (reversed string)
Strings in Python
3. Slicing and Striding Strings:
 String Striding: Specify a step size for slicing.

Example :
my_string = "Python is awesome!“

reversed_string = my_string[::-1]
every_other_char = my_string[::2]
Output:
"!emosewa si nohtyP“
"Pto i aewm!"
Strings in Python
3. Slicing and Striding Strings:
 String Striding: Negative Indices: Access characters from the end
of the string.

Example :
my_string = "Python is awesome!"

last_char = my_string[-1]

Output:
!
Strings in Python
3. Slicing and Striding Strings:
 String Striding:

Figure: Diagram showing slicing (0-based indexing) with different start, stop, and
step values.
Strings in Python
4. String Operators:
Python supports various operators for strings.
Operator Description Example
+ Concatenation 'Hello' + 'World'
* Repetition 'Hello' * 3
in Membership (substring check) 'H' in 'Hello'
not in Membership (not a substring) 'z' not in 'Hello'

Example :
print('Hello' + ' ' + 'World!') # Output: Hello World!
print('Hello ' * 3) # Output: Hello Hello Hello
print('o' in 'Hello') # Output: True
Strings in Python
5. Common String Methods:
Python provides several built-in methods for string manipulation.
Method Description Example
upper() Converts to uppercase 'hello'.upper()
lower() Converts to lowercase 'HELLO'.lower()
Removes whitespace from
strip() ' hello '.strip()
both ends
Replaces occurrences of a
replace(a,b) 'hello'.replace('h','y')
with b
split() Splits a string into a list 'a,b,c'.split(',')

Example :
sentence = " Hello World! "
print(sentence.strip()) # Output: Hello World!
print(sentence.upper()) # Output: HELLO WORLD!
print(sentence.replace("Hello", "Hi")) # Output: Hi World!
Strings in Python
6. String Formatting with 'str.format':
 String formatting allows you to insert variables into strings
dynamically.
 Use curly braces {} as placeholders.

Basic Formatting Example :


name = "Ram"
age = 25
message = "My name is {} and I am {} years old.".format(name, age)
print(message)

Output:
My name is Ram and I am 25 years old.
Strings in Python
6. String Formatting with 'str.format':
• String formatting allows you to insert variables into strings
dynamically.
Positional and Keyword Arguments - Example :
name = "Ram"
age = 25

message = "My name is {0} and I am {1} years old.".format(name, age)


message2 = "My name is {name} and I am {age} years old.".format(name="Bheem", age=30)

Output:
My name is Ram and I am 25 years old.
My name is Bheem and I am 30 years old.
Strings in Python
6. String Formatting with 'str.format':
String formatting allows you to insert variables into strings dynamically.
Formatting Numbers - Example :
pi = 3.14159
print("Pi is approximately {:.2f}".format(pi))

Output:
Output: Pi is approximately 3.14
Strings in Python
6. String Formatting with 'str.format':
String formatting allows you to insert variables into strings dynamically.

Figure: Diagram showing placeholders {} and how variables are mapped to them
during runtime.
Strings in Python
6. String Formatting with 'str.format':
String formatting allows you to insert variables into strings dynamically.

Example: Write a formatted string that dynamically includes a person's name,


age, and profession
name = “Sita"
age = 24
profession = "Engineer"
formatted_string = "My name is {0}, I am {1} years old, and I work as a {2}.".format(name, age, profession)
print(formatted_string)
Strings in Python
6. String Formatting with 'str.format':
String formatting allows you to insert variables into strings dynamically.

Example: Write a formatted string that dynamically includes a person's name,


age, and profession
name = “Sita"
age = 24
profession = "Engineer"
formatted_string = "My name is {0}, I am {1} years old, and I work as a {2}.".format(name, age, profession)
print(formatted_string)
Strings in Python
6. String Formatting with 'str.format':
• Custom Formatting: Use field specifiers within curly braces for more
control..
Example:

number = 1234.5678
formatted_number = f"{number:.2f}"

Output:
"1234.57"
Strings in Python
String Operators and Methods:
 Concatenation: Combine strings using the + operator.
Example:

greeting = "Hello"
name = "Ram"
message = greeting + ", " + name + "!"
Strings in Python
String Operators and Methods:
 Replication: Repeat a string using the * operator.
Example:

repeated_string = "Ram" * 3

Output:
"RamRamRam"
Strings in Python
String Operators and Methods:
 Common Methods
 upper(): Converts to uppercase.
 lower(): Converts to lowercase.
 capitalize(): Capitalizes the first letter.
 count(): Counts occurrences of a substring.
 replace(): Replaces a substring with another.
 split(): Splits a string into a list of substrings.
 join(): Joins a list of strings into a single string.
Strings in Python
String Operators and Methods:
 Common Methods
 Case Manipulation: upper(), lower(), capitalize(), title(), swapcase()
 Searching and Finding: count(), find(), rfind()
 Replacing and Modifying: replace(), startswith(), endswith(), strip(),
lstrip(), rstrip()
 Splitting and Joining: split(), join(), splitlines()
 Character Tests: isalpha(), isdigit(), isalnum(), isspace()
Strings in Python
6. String Formatting with 'str.format':
String formatting allows you to insert variables into strings dynamically.

Example: Write a formatted string that dynamically includes a person's name,


age, and profession
name = “Sita"
age = 24
profession = "Engineer"
formatted_string = "My name is {0}, I am {1} years old, and I work as a {2}.".format(name, age, profession)
print(formatted_string)
Collections Data Types:
Tuples
Lists
Sets
Dictionaries
Iterating and Copying collections
Thank You

You might also like