KEMBAR78
Class 11th Chapter String | PDF | String (Computer Science) | Letter Case
0% found this document useful (0 votes)
5 views5 pages

Class 11th Chapter String

This document provides an overview of strings in Python, detailing their definition, traversal, indexing, slicing, operators, and various built-in functions. It explains how to create strings, access their characters, and manipulate them using different methods and operators. Examples are provided for each concept to illustrate their usage in Python programming.

Uploaded by

kunalmalik1616
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 views5 pages

Class 11th Chapter String

This document provides an overview of strings in Python, detailing their definition, traversal, indexing, slicing, operators, and various built-in functions. It explains how to create strings, access their characters, and manipulate them using different methods and operators. Examples are provided for each concept to illustrate their usage in Python programming.

Uploaded by

kunalmalik1616
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/ 5

Class 11th Chapter String

1. String Definition
A string in Python is an immutable sequence of characters. It is a fundamental data type
used to represent text. Strings can be created by enclosing characters in single quotes ('...'),
double quotes ("..."), or triple quotes ('''...''' or """..."""). Triple quotes are useful for multi-line
strings.
Examples:
# Single quotes
my_string1 = 'Hello, World!'

# Double quotes
my_string2 = "Python Programming"

# Triple quotes for multi-line string


my_string3 = """This is a
multi-line string
in Python."""

2. Traversing: means accessing characters one by one.


You can iterate over the characters of a string using a for loop.
Example:
s = "Python"
for char in s:
print(char, end=' ')
# Output: P y t h o n

Indexing:
Strings in Python are zero-indexed, meaning the first character is at index 0.
* Forward Indexing: Starts from 0 for the first character, 1 for the second, and so on and the
last character is at length -1 index.
* Backward Indexing: Starts from -1 for the last character, -2 for the second to last, and so
on. First character is at - (length) index.
Example:
s = "Hello"
print(s[0]) # Output: H (forward index 0)
print(s[4]) # Output: o (forward index 4)
print(s[-1]) # Output: o (backward index -1)
print(s[-5]) # Output: H (backward index -5)

Slicing: string slice is used to extract a substring from a string. The syntax is
[start:stop:step].
* start: The index where the slice begins (inclusive).
* stop: The index where the slice ends (exclusive).
* step: The step size for the slice.
Example:
s = "Programming"
print(s[2:7]) # Output: ogram (from index 2 up to, but not including, 7)
print(s[:5]) # Output: Progr (from the beginning to index 5)
print(s[5:]) # Output: amming (from index 5 to the end)
print(s[::2]) # Output: Pormig (every second character)
print(s[::-1]) # Output: gnimmargorP (reverses the string)

3. String Operators
* Concatenation (+): Joins two or more strings.
s1 = "Hello"
s2 = "World"
result = s1 + " " + s2
print(result) # Output: Hello World

* Repetition (*): Repeats a string a specified number of times.


s = "Python"
repeated = s * 3
print(repeated) # Output: PythonPythonPython
Note:- String can be multiplied only by an integer.
* Membership operators (in, not in): Checks if a substring is present in a string.
s = "Programming"
print("gram" in s) # Output: True
print("xyz" not in s) # Output: True

* Relational Operators (==, !=, <, >, <=, >=): Compares strings lexicographically (based on
ASCII values).
s1 = "apple"
s2 = "Apple"
print(s1 == s2) # Output: False
print(s1 > s2) # Output: True (A comes before a)

4. String Functions
* len(string): Returns the length of the string.
s = "Python"
print(len(s)) # Output: 6

* capitalize(): Returns a copy of the string with its first character capitalized and the rest
lowercase.
s = "hello world"
print(s.capitalize()) # Output: Hello world

* title(): Returns a title-cased version of the string, where each word starts with an
uppercase character and the rest are lowercase.
s = "hello world"
print(s.title()) # Output: Hello World

* upper(): Returns a copy of the string converted to uppercase.


s = "Hello"
print(s.upper()) # Output: HELLO

* lower(): Returns a copy of the string converted to lowercase.


s = "Hello"
print(s.lower()) # Output: hello

* swapcase(): Returns a copy of the string with uppercase characters converted to


lowercase and vice versa.
s = "HeLlO wOrLd"
print(s.swapcase()) # Output: hElLo WoRlD

* istitle(): Returns True if the string is title-cased, otherwise False.


s1 = "Hello World"
s2 = "hello world"
print(s1.istitle()) # Output: True
print(s2.istitle()) # Output: False

* isupper(): Returns True if all cased characters in the string are uppercase, otherwise
False.
s1 = "HELLO"
s2 = "Hello"
print(s1.isupper()) # Output: True
print(s2.isupper()) # Output: False

* islower(): Returns True if all cased characters in the string are lowercase, otherwise
False.
s1 = "hello"
s2 = "Hello"
print(s1.islower()) # Output: True
print(s2.islower()) # Output: False

* isalpha(): Returns True if all characters in the string are alphabetic and there is at least
one character, otherwise False.
print("Python".isalpha()) # Output: True
print("Python3".isalpha()) # Output: False

* isalnum(): Returns True if all characters in the string are alphanumeric (alphabetic or
numeric) and there is at least one character, otherwise False.
print("Python3".isalnum()) # Output: True
print("Py thon".isalnum()) # Output: False

* isspace(): Returns True if all characters in the string are whitespace and there is at least
one character, otherwise False.
print(" ".isspace()) # Output: True
print("Hello".isspace()) # Output: False

* isdigit(): Returns True if all characters in the string are digits and there is at least one
character, otherwise False.
print("123".isdigit()) # Output: True
print("123a".isdigit()) # Output: False
* count(substring, start, end): Returns the number of non-overlapping occurrences of a
substring.
s = "hello world hello"
print(s.count("o")) # Output: 3
print(s.count("hello"))# Output: 2

* partition(separator): Splits the string into three parts at the first occurrence of the
separator: the part before, the separator itself, and the part after. Returns a tuple.
s = "name=john"
print(s.partition("=")) # Output: ('name', '=', 'john')

* split(separator): Splits the string into a list of strings using the separator as the delimiter.
If no separator is given, it splits by whitespace.
s = "one two three"
print(s.split()) # Output: ['one', 'two', 'three']
s2 = "a,b,c"
print(s2.split(',')) # Output: ['a', 'b', 'c']

* join(iterable): Joins the elements of an iterable (like a list) into a single string, using the
string as the separator.
my_list = ['Hello', 'World']
print(" ".join(my_list)) # Output: Hello World
print("-".join(my_list)) # Output: Hello-World

* strip(chars): Returns a copy of the string with leading and trailing whitespace (or specified
chars) removed.
s = " hello world "
print(s.strip()) # Output: 'hello world'
s2 = "abcde"
print(s2.strip('a')) # Output: 'bcde'

* lstrip(chars): Returns a copy of the string with leading whitespace (or specified chars)
removed.
s = " hello world "
print(s.lstrip()) # Output: 'hello world '

* rstrip(chars): Returns a copy of the string with trailing whitespace (or specified chars)
removed.
s = " hello world "
print(s.rstrip()) # Output: ' hello world'

* replace(old, new, count): Returns a copy of the string with all occurrences of old
replaced by new.
s = "hello world"
print(s.replace("o", "x")) # Output: hellx wxrld
print(s.replace("o", "x", 1)) # Output: hellx world (replaces only the first occurrence)
* find(substring, start, end): Returns the lowest index of the substring if found. Returns -1
otherwise.
s = "hello world"
print(s.find("o")) # Output: 4
print(s.find("o", 5)) # Output: 7 (starts searching from index 5)
print(s.find("xyz")) # Output: -1

* index(substring, start, end): it works similar to find(), but raises a ValueError if the
substring is not found.
s = "hello world"
print(s.index("o")) # Output: 4
try:
s.index("xyz")
except ValueError as e:
print(e) # Output: substring not found

* startswith(prefix, start, end): Returns True if the string starts with the specified prefix.
s = "Python"
print(s.startswith("Py")) # Output: True
print(s.startswith("thon", 2)) # Output: True (starts with "thon" at index 2)

* endswith(suffix, start, end): Returns True if the string ends with the specified suffix.
s = "Python"
print(s.endswith("on")) # Output: True
print(s.endswith("th", 0, 4)) # Output: True (ends with "th" in the slice up to index 4)

You might also like