0% found this document useful (0 votes)
8 views

String

The document explains nested loops and provides an example of generating a pattern using them. It also covers strings, including their definition, indexing, slicing, mutability, and various string operations and methods in Python. Additionally, it discusses string methods such as concatenation, repetition, membership, and built-in functions for manipulating strings.
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)
8 views

String

The document explains nested loops and provides an example of generating a pattern using them. It also covers strings, including their definition, indexing, slicing, mutability, and various string operations and methods in Python. Additionally, it discusses string methods such as concatenation, repetition, membership, and built-in functions for manipulating strings.
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/ 8

Nested loops

Nested loops refers to a loop within a loop.


Example: Generating a pattern
n = int(input("Enter the number of rows: "))
for i in range(n):
for j in range(i+1):
print("*", end="")
print()

Output
Enter the number of rows: 5
*
**
***
****
*****

String
String: String is a sequence of UNICODE characters. A string can be created by enclosing one or more
characters in single, double or triple quotes (' ' or '' '' or ''' ''').
Example
>>> str1 = 'Python'
>>> str2 = "Python"
>>> str3 = '''Multi Line
String'''
>>> str4 = """Multi Line
String"""

Terminology

Whitespace Characters: Those characters in a string that represent horizontal or vertical space.
Example: space (' '), tab ('\t'), and newline ('\n')

75
Indexing in Strings
● Indexing is used to access individual characters in a string using a numeric value.
● The index of the first character (from left) in the string is 0 and the last character is n-1
● The index can also be an expression including variables and operators but the expression must
evaluate to an integer
● Forward indexing, also known as positive indexing, starts from left to right, with the first character
having index 0, second character having index 1, and so on.
● Backward indexing, also known as negative indexing, starts from right to left, with the last character
having index -1, second-last character having index -2, and so on

Example
>>> str1 = 'Python' >>> str1 = 'Python'
>>> str1[0] >>> str1[2+3]
'P' 'n'

Slicing
Slicing is the process of extracting a substring from a given string. It is done using the operator ':'.
Syntax : string[start:end:step].
start : 'start' is the starting index of the substring (inclusive).
end : 'end' is the ending index of the substring (exclusive)
step : 'step' is the difference between the index of two consecutive elements. Default value is 1
Case-1 Case-2 Case-3 Case-4
print(str1[:3]) print(str1[1:4]) print(str1[0:5:2]) print(str1[-5:-1])

Output Output Output Output


PYT YTH PTO YTHO
Case-5 Case-6 Case-7
print(str1[-1:-4]) print(str1[:-5:- print(str1[:-5])
1])
Output Output
'' Output P
NOHT

76
Mutable Object
If the value of an object can be changed after it is created, It is called mutable object
Example
Lists, Set and dictionaries.

Immutable Object
If the value of an object cannot be changed after it is created, it is called immutable object
Example
Numeric, String and Tuple

String is Immutable
A string is an immutable data type. It means that the value (content) of a string object cannot be changed
after it has been created. An attempt to do this would lead to an error.
Example
>>> str1 = 'Python'
>>> str1[1]='Y'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment

Traversal of a String
Accessing the individual characters of string i.e. from first
1. Using only for Loop
str1 = 'Computer'
for ch in str1:
print(ch, end=' ')

2. Using For Loop and range function


str1 = 'Computer'
for ch in range(0,len(str1)):
print(str1[ch],end=' ')

3. Using while Loop


str1 = 'Computer'
i = 0
while i < len(str1):
print(str1[i],end = ' ')
i+= 1

77
String Operations
We can perform various operations on string such as concatenation, repetition, membership and slicing.

Concatenation
Operator : +
>>> str1 = "Python"
>>> str2 = "Programming"
>>> str1 + str2
'PythonProgramming'

Repetition
Use : To repeat the given string multiple times.
Repetition operator : *
>>> str1 = "Hello "
>>> str1*5
'Hello Hello Hello Hello Hello'

Membership
Membership is the process of checking whether a particular character or substring is present in a sequence
or not. It is done using the 'in' and 'not in' operators.
Example
>>> str1 = "Programming in Python"
>>> "Prog" in >>> "ming in" >>> "Pyth " in >>> "Pyth "
str1 in str1 str1 not in str1
True True False True

String Methods/Functions

Python has several built-in functions that allow us to work with strings

78
len() capitalize()
Returns the length of the given string converts the first character of a string to capital
>>> str1 = 'Hello World!' (uppercase) letter and rest in lowercase.
>>> len(str1) str1 = "python Programming for
12 11th"
str1.capitalize()
'Python programming for 11th'
title() lower()
converts the first letter of every word in the string Returns the string with all uppercase letters
in uppercase and rest in lowercase converted to lowercase
>>> str1 = "python ProGramming >>> str1 = "PYTHON PROGRAMMING for
for 11th" 11th"
>>> str1.title() >>> str1.lower()
'Python Programming For 11Th' 'python programming for 11th'

upper() count()
Returns the string with all lowercase letters Returns number of times a substring occurs in the
converted to uppercase given string
>>> str1 = "python programming >>> str1 = "python programming for
for 11th" 11th"
>>> str1.upper() >>> str1.count("p")
'PYTHON PROGRAMMING FOR 11TH' 2
>>> str1.count("pyth")
1

find() index()
Returns the index of the first occurrence of Same as find() but raises an exception if the
substring in the given string. If the substring is substring is not present in the given string
not found, it returns -1 >>> str1 = "python programming for
>>> str1 = "python programming 11th"
for 11th" >>> str1.index('r')
>>> str1.find('r') 8
8 >>> str1.index('u')
>>> str1.find('u') Traceback (most recent call last):
-1 File "<stdin>", line 1, in
<module>
ValueError: substring not found

79
isalnum() isalpha()
The isalnum() method returns True if all Returns True if all characters in the string are
characters in the string are alphanumeric (either alphabets, Otherwise, It returns False
alphabets or numbers). If not, it returns False. >>> 'Python'.isalpha()
>>> str1 = 'HelloWorld' True
>>> str1.isalnum() >>> 'Python 123'.isalpha()
True False
>>> str1 = 'HelloWorld2'
>>> str1.isalnum()
True

isdigit() isspace()
returns True if all characters in the string are Returns True if has characters and all of them are
digits, Otherwise, It returns False white spaces (blank, tab, newline)
>>> '1234'.isdigit() >>> str1 = ' \n \t'
True >>> str1.isspace()
>>> '123 567'.isdigit() True
False >>> str1 = 'Hello \n'
>>> str1.isspace()
False

islower() isupper()
returns True if the string has letters all of them returns True if the string has letters all of them are
are in lower case and otherwise False. in upper case and otherwise False.
>>> str1 = 'hello world!' >>> str1 = 'HELLO WORLD!'
>>> str1.islower() >>> str1.isupper()
True True
>>> str1 = 'hello 1234' >>> str1 = 'HELLO 1234'
>>> str1.islower() >>> str1.isupper()
True True
>>> str1 = 'hello ??' >>> str1 = 'HELLO ??'
>>> str1.islower() >>> str1.isupper()
True True

80
strip() lstrip()
Returns the string after removing the whitespaces Returns the string after removing the whitespaces
both on the left and the right of the string only on the left of the string
>>> str1 = ' Hello World! ' >>> str1 = ' Hello World! '
>>> str1.strip() >>> str1.lstrip()
'Hello World!' 'Hello World! '

rstrip() replace(oldstr,newstr)
Returns the string after removing the whitespaces used to replace a particular substring in a string
only on the right of the string with another substring
>>> str1 = ' Hello World! ' >>> str1 = 'Hello World!'
>>> str1.rstrip() >>> str1.replace('o','*')
' Hello World!' 'Hell* W*rld!'
partition() split()
The partition() function is used to split a string Returns a list of words delimited by the specified
into three parts based on a specified separator. substring. If no delimiter is given then words are
>>> str1 = 'India is a Great Country' separated by space.
>>> str1.partition('is') >>> str1 = 'India is a Great Country'
('India ', 'is', ' a Great Country') >>> str1.split()
>>> str1.partition('are') ['India','is','a','Great', 'Country']
('India is a Great Country',' ',' ') >>> str1 = 'India is a Great Country'
>>> str1.split('a')
['Indi', ' is ', ' Gre', 't Country']

81
startswith() join()
startswith() function is used to check whether a str.join(sequence)
given string starts with a particular substring. returns a string in which the string elements of
sequence have been joined by str separator. if few
endswith() of the members of the sequence are not string, error
endswith() function is used to check whether a is generated.
given string ends with a particular substring. >>> '*-*'.join('Python')
'P*-*y*-*t*-*h*-*o*-*n'
str = "Python Programming >>> '*-
Language" *'.join(['Ajay','Abhay','Alok'])
print(str.startswith("Pyt")) 'Ajay*-*Abhay*-*Alok'
print(str.startswith("Pyth")) >>> '*-
print(str.endswith("age")) *'.join(['Ajay','Abhay',123])
print(str.endswith("uage")) Traceback (most recent call last):
print(str.startswith("Pyts")) File "<stdin>", line 1, in
<module>
Output TypeError: sequence item 2:
True expected str instance, int found
True
True
True
False

82

You might also like