0% found this document useful (0 votes)
20 views9 pages

Unit 3 Strings

The document provides an overview of Python strings, including their declaration, operations, built-in functions, formatting methods, and comparison techniques. It explains string manipulation methods such as concatenation, slicing, and various built-in functions like len(), lower(), and replace(). Additionally, it covers string encoding, decoding, and practical examples for reversing strings, finding the longest word, and checking for anagrams.

Uploaded by

tiwarinitish960
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)
20 views9 pages

Unit 3 Strings

The document provides an overview of Python strings, including their declaration, operations, built-in functions, formatting methods, and comparison techniques. It explains string manipulation methods such as concatenation, slicing, and various built-in functions like len(), lower(), and replace(). Additionally, it covers string encoding, decoding, and practical examples for reversing strings, finding the longest word, and checking for anagrams.

Uploaded by

tiwarinitish960
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/ 9

Python Strings

In Python, a string is a sequence of characters enclosed in quotes (single, double, or triple


quotes). Strings are immutable, meaning their contents cannot be modified after creation.

Declaration

Strings can be declared using single quotes, double quotes, or triple quotes.

Single quotes

my_string = 'Hello, World!'

Double quotes

my_string = "Hello, World!"

Triple quotes (for multiline strings)

my_string = '''This is a

multiline string.'''

Operations

Python strings support various operations, including:

+ Concatenation: Combining two or more strings using the + operator.

first_name = 'John'

last_name = 'Doe'

full_name = first_name + ' ' + last_name

print(full_name) # Output: John Doe


* Repetition: Repeating a string using the * operator.

my_string = 'Hello'

repeated_string = my_string * 3

print(repeated_string) # Output: HelloHelloHello

Indexing: Accessing individual characters in a string using their index.

my_string = 'Hello'

print(my_string[0]) # Output: H

* Slicing: Extracting a subset of characters from a string using slicing.

my_string = 'Hello, World!'

print(my_string[0:5]) # Output: Hello

Built-in Functions

Python provides several built-in functions for working with strings, including:

len(): Returns the length of a string.

my_string = 'Hello'

print(len(my_string)) # Output: 5

lower(): Converts a string to lowercase.

my_string = 'HELLO'

print(my_string.lower()) # Output: hello

upper(): Converts a string to uppercase.

my_string = 'hello'

print(my_string.upper()) # Output: HELLO


strip(): Removes leading and trailing whitespace from a string.

my_string = ' Hello '

print(my_string.strip()) # Output: Hello

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

my_string = 'apple,banana,cherry'

print(my_string.split(',')) # Output: ['apple', 'banana', 'cherry']

join(): Concatenates a list of strings into a single string.

my_list = ['apple', 'banana', 'cherry']

print(','.join(my_list)) # Output: apple,banana,cherry

replace(): Replaces occurrences of a substring with another substring.

my_string = 'Hello, World!'

print(my_string.replace('World', 'Earth')) # Output: Hello, Earth!

find(): Returns the index of the first occurrence of a substring.

my_string = 'Hello, World!'

print(my_string.find('World')) # Output: 7

count(): Returns the number of occurrences of a substring.

my_string = 'Hello, World! Hello again!'

print(my_string.count('Hello')) # Output: 2

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

my_string = 'hello'

print(my_string.capitalize()) # Output: Hello


title(): Converts a string to title case.

my_string = 'hello world'

print(my_string.title()) # Output: Hello World

swapcase(): Swaps the case of characters in a string.

my_string = 'Hello World'

print(my_string.swapcase()) # Output: hELLO wORLD

startswith(): Checks if a string starts with a specified substring.

my_string = 'Hello World'

print(my_string.startswith('Hello')) # Output: True

endswith(): Checks if a string ends with a specified substring.

my_string = 'Hello World'

print(my_string.endswith('World')) # Output: True

String Formatting
Python provides several ways to format strings, including:

f-strings

f-strings are a convenient way to embed expressions inside string literals. They were
introduced in Python 3.6 and have become a popular choice for string formatting.

name = 'John'

age = 30

print(f'My name is {name} and I am {age} years old.')

# Output: My name is John and I am 30 years old.


String Formatting Operators
Python also provides string formatting operators, such as %s, %d, and %f, which can be used
to format strings.

name = 'John'

age = 30

print('My name is %s and I am %d years old.' % (name, age))

# Output: My name is John and I am 30 years old.

String Formatting Methods


The str.format() method is another way to format strings in Python. It provides more
flexibility and control over the formatting process.

name = 'John'

age = 30

print('My name is {} and I am {} years old.'.format(name, age))

# Output: My name is John and I am 30 years old.

String Comparison
Strings can be compared using various operators, such as ==, !=, <, >, <=, and >=. These
operators compare the strings lexicographically, which means they compare the strings
character by character based on their ASCII values.

print('apple' == 'apple') # Output: True

print('apple' < 'banana') # Output: True


String Membership
The in operator can be used to check if a substring is present in a string.

my_string = 'Hello, World!'

print('World' in my_string) # Output: True

String Iteration
Strings can be iterated over using a for loop, which allows you to access each character in
the string.

my_string = 'Hello'

for char in my_string:

print(char)

# Output:

#H

#e

#l

#l

#o

String Encoding
Python strings can be encoded into bytes using various encoding schemes, such as UTF-8,
ASCII, and ISO-8859-1.

my_string = 'Hello, World!'

encoded_string = my_string.encode('utf-8')

print(encoded_string) # Output: b'Hello, World!'


String Decoding
Bytes can be decoded into strings using the decode() method.

encoded_string = b'Hello, World!'

decoded_string = encoded_string.decode('utf-8')

print(decoded_string) # Output: Hello, World!

1. Reverse a String
string = "hello"

reversed_string = string[::-1]

print(reversed_string)

o/p: olleh

2. Find Longest Word


sentence = "Python programming is powerful"

words = sentence.split()

longest = max(words, key=len)

print("Longest word:", longest)

# Output: Longest word: programming

3. Replace Spaces with Hyphens


text = "Python is awesome"

new_text = text.replace(" ", "-")


print(new_text)

# Output: Python-is-awesome

5. Check Anagrams
s1 = "listen"

s2 = "silent"

is_anagram = sorted(s1) == sorted(s2)

print(is_anagram)

# Output: True

6. Write a program to find and print all words from a


sentence that start with a given letter.
sentence = "Python programming is popular"

letter = "p"

words = [word for word in sentence.split() if word.lower().startswith(letter)]

print(words)

# Output: ['programming', 'popular']

7. Caesar Cipher (Shift by 1)


text = "abcXYZ"

shifted_text = ''

for char in text:


if char.isalpha():

if char.islower():

shifted_text += chr((ord(char) - ord('a') + 1) % 26 + ord('a'))

else:

shifted_text += chr((ord(char) - ord('A') + 1) % 26 + ord('A'))

else:

shifted_text += char

print(shifted_text)

# Output: bcdYZA

ord() Function
The ord() function returns the Unicode code point for a given character. In other words, it
gives you the ASCII value of a character.

print(ord('A')) # Output: 65

print(ord('a')) # Output: 97

chr() Function
The chr() function does the opposite of ord(). It returns the character represented by a
specific Unicode code point.

print(chr(65)) # Output: A

print(chr(97)) # Output: a

You might also like