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

String

The document provides a comprehensive overview of strings in Python, defining them as immutable collections of characters that can be created using single, double, or triple quotes. It covers string indexing, accessing characters, string operators (concatenation, repetition, membership, and comparison), slicing, and various built-in string functions. Examples are provided throughout to illustrate the concepts and functionalities associated with strings.

Uploaded by

arnavpratap.6969
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

String

The document provides a comprehensive overview of strings in Python, defining them as immutable collections of characters that can be created using single, double, or triple quotes. It covers string indexing, accessing characters, string operators (concatenation, repetition, membership, and comparison), slicing, and various built-in string functions. Examples are provided throughout to illustrate the concepts and functionalities associated with strings.

Uploaded by

arnavpratap.6969
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

STRING IN PYTHON

Definition: String is a collection of characters. Strings can be created by enclosing


characters inside a single quote or double-quotes. Even triple quotes can be used in
Python but generally used to represent multiline strings. Python does not have a
character data type, a single character is simply a string with a length of 1.

Basics of String:
• Strings are immutable means that the contents of the string cannot be changed
after it is created. At the same memory address, the new value cannot be stored.
Python does not allow the programmer to change a character in a string.
Example:
>>>str='jaipur'
>>>str[0]='J'
TypeError: 'str' object does not support item assignment
As shown in the above ex

ample, str has the value “jaipur”. An attempt to replace ‘j’ in the string by
‟J‟ displays a TypeError.
• Each character has its index or can be accessed using its index.
• String in python has two-way index for each location. (0, 1, 2, ……. In the forward
direction and -1, -2, -3, …….. in the backward direction.)
Example:
0 1 2 3 4 5 6
T E A C H E R
-7 -6 -5 -4 -3 -2 -1

• The index of string in forward direction starts from 0 and in backward direction
starts from -1.
• The size of string is total number of characters present in the string. (If there are
n characters in the string, then last index in forward direction would be n-1 and
last index in backward direction would be –n.)
• String are stored each character in contiguous location.
• The character assignment is not supported in string because strings are
immutable.

Accessing Characters in a String


As we know, string is a collection of characters and individual character can be accessed
by its position called index. Square brackets can be used to access elements of the string.

Example:
>>>s=”TEACHER”
>>>s[1]
‘E’ # returns index 1 position
>>>s[-4]
‘C’ #returns index -4 position

Traversing a String: Access all elements of string, one character at a time.


s=”TEACHER” s=”TEACHER”
for ch in s : for i in range(len(s)):
print(ch) print(s[i])

>>>len(s) # returns length of string.

String Operators:
A). String concatenation Operator: Concatenation means to join two values. In
Python, + symbol is used to concatenate the strings.
>>>name="Jay"
>>>msg="Hello "
>>>print(msg+name)
'Hello Jay' #concatenated string
Note: You cannot concate numbers and strings as operands with + operator.
Example:
>>>7+’4’ # unsupported operand type(s) for +: 'int' and 'str'
It is invalid and generates an error.
B). String repetition Operator: It is also known as String replication operator.
Replication can be performed by using * operator between the string. It will repeat the
string n times, where n is the integer providedple:
>>>s="Ha"
>>> s*3
'HaHaHa' #Replication
Note:You cannot have strings as n=both the operands with * operator.
Example:
>>>”Ha” * “Ha” # can't multiply sequence by non-int of type 'str'
It is invalid and generates an error.
C). Membership Operators: In and not in are two membership operators to find the
appearance of a substring inside the string.in – Returns True if a character or a substring
exists in the given string; otherwise, False
not in - Returns True if a character or a substring does not exist in the given string;
otherwise, False
Example: >>> "T" in "TEACHER"
True
>>> "ea" in "TEACHER "
False
>>>"CH" not in "TEACHER "
False
D). Comparison Operators: These operators compare two strings character by
character according to their ASCII value. ASCII Values can be finding out by given
functions.
Characters ASCII (Ordinal) Value
‘0’ to ‘9’ 48 to 57
‘A’ to ‘Z’ 65 to 90
‘a’ to ‘z’ 97 to 122

Function Description
ord(<character>) Returns ordinal value of a
character
chr(<value>) Returns the corresponding
character
Example:
>>> 'abc'>'abcD'
False
>>> 'ABC'<'abc'
True
>>> 'abcd'>'aBcD'
True
>>> 'aBcD'<='abCd'
True
>>> ord('b')
98
>>> chr(65)
'A'

Slicing in Strings: Extracting a subpart from a main string is called slicing .It is done
by using a range of indices.
Syntax:
>>>string-name[start:stop:step]
Note: it will return a string from the index start to stop-1.
Example:
>>> s="TEACHER"
0 1 2 3 4 5 6
T E A C H E R
-7 -6 -5 -4 -3 -2 -1

>>> s[2:6:1]
'ACHE'
>>> s[6:1:-1]
'REHCA'
>>> s[0:10:2]
'TAHR'
>>> s[-8:-3:1]
'TEAC
>>> s[ : 6 : 1] # Missing index at start is considered as 0.
'TEACHE'
>>> s[2 : :2] # Missing index at stop is considered as last index.
'AHR'
>>> s[3:6: ] # Missing index at step is considered as 1.
'CHE'
>>> s[ : :-1]
'REHCAET'
>>> s[2: :]+s[ :2 :]
'ACHERTE'
>>> s[1: 5:-1]
‘‘

Built-in functions of string:

str=”data structure” s1= “hello365” s2= “python” s3 = ‘4567’


s4 = ‘ ‘ s5= ‘comp34%@’
S. Function Description Example
No.
1 len( ) Returns the length of a string >>>print(len(str))
14
2 capitalize( ) Returns the copy of the string with its >>> s1.capitalize()
first character capitalized and the rest 'Hello365'
of the letters are in lowercased.
3 find(sub,start,en Returns the index of the first >>>s2.find("thon",1,7)
d) occurence of a substring in the given 3
string (case-sensitive). If the >>> str.find("ruct",8,13)
substring is not found it returns -1. -1
4 isalnum( ) Returns True if all characters in the >>>s1.isalnum( )
string are alphanumeric (either True
alphabets or numbers). If not, it >>>s2.isalnum( )
returns False. True
>>>s3.isalnum( )
True
>>>s4.isalnum( )
False
>>>s5.isalnum( )
False
5 isalpha( ) Returns True if all characters in the >>>s1.isalpha( )
string arealphabetic. False otherwise. False
>>>s2.isalpha( )
True
>>>s3.isalpha( )
False
>>>s4.isalpha( )
False
>>>s5.isalpha( )
False
6 isdigit( ) Returns True if all the characters in >>>s1.isdigit( )
the string aredigits. False otherwise. False
>>>s2.isdigit( )
False
>>>s3.isdigit( )
True
>>>s4.isdigit( )
False
>>>s5.isdigit( )
False
7 islower( ) Returns True if all the characters in >>> s1.islower()
the string arelowercase. False True
otherwise. >>> s2.islower()
True
>>> s3.islower()
False
>>> s4.islower()
False
>>> s5.islower()
True
8 isupper( ) Returns True if all the characters in
>>> s1.isupper()
the string areuppercase. False False
otherwise. >>> s2.isupper()
False
>>> s3.isupper()
False
>>> s4.isupper()
False
>>> s5.isupper()
False
9 isspace( ) Returns True if there are only whitespace
>>> " ".isspace()
characters in the string. False
True
>>> "".isspace()
False
10 lower( ) Converts a string in lowercase >>> "HeLlo".lower()
characters. 'hello'
11 upper( ) Converts a string in uppercase >>> "hello".upper()
characters. 'HELLO'
12 lstrip( ) Returns a string after removing >>> str="data structure"
the leading characters. (Left side). >>> str.lstrip('dat')
if used without any argument, it ' structure'
removes theleading whitespaces. >>> str.lstrip('data')'
structure'
>>> str.lstrip('at')
'data structure'
>>> str.lstrip('adt')
' structure'
>>> str.lstrip('tad')
' structure'
13 rstrip( ) Returns a string after removing the >>> str.rstrip('eur')
trailingcharacters. (Right side). 'data struct'
if used without any argument, it >>> str.rstrip('rut')
removes thetrailing whitespaces. 'data structure'
>>> str.rstrip('tucers')'data
'
14 split( ) Splits the string from the specified >>> str="Data Structure"
separator and returns a list object >>> str.split( )
with string elements. ['Data', 'Structure']

You might also like