Strings are sequences of characters that can be indexed, sliced, and operated on using various operators and methods in Python. Some key points about strings include:
- Strings are immutable sequences that are indexed starting from 0 in the forward direction and -1 in the backward direction.
- Common string operations include concatenation, membership testing, comparison, and slicing to extract substrings.
- Built-in string methods allow checking string properties (like isalpha(), isdigit()) and modifying case (like lower(), upper()).
- Strings can be traversed and individual characters accessed using a for loop or string indexing.
Strings are sequences of characters that can be indexed, sliced, and operated on using various operators and methods in Python. Some key points about strings include:
- Strings are immutable sequences that are indexed starting from 0 in the forward direction and -1 in the backward direction.
- Common string operations include concatenation, membership testing, comparison, and slicing to extract substrings.
- Built-in string methods allow checking string properties (like isalpha(), isdigit()) and modifying case (like lower(), upper()).
- Strings can be traversed and individual characters accessed using a for loop or string indexing.
String:- Sequence of characters enclosed in single, double or triple quotation marks.
Basics of String: Strings are immutable in python. It means it is unchangeable. At the same memory address, the new value cannot be stored. 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 7 K E N D R I Y A -8 -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. Example: str = “kendriya” str[2] = „y‟ # it is invalid. Individual letter assignment not allowed in python Traversing a String: • It means accessing the individual characters of string i.e. from first character to last character. • Every character in string is at different index position i.e. from 0 to size-1 • For loop can be used to traverse the string very easily Example name="lovely" for ch in name: print(ch,'-',end='') The above code will print l-o-v-e-l-y- STRING OPERATORS Two basic operators + and * are allowed + is used for concatenation (joining) * Is used for replication (repetition) EXAMPLE A=“Tom” B=“Jerry” C=A+” & ”+B print (C) # Return Tom & Jerry Note: you cannot add number and string using + Line=“ go” print (Line*3, ” Govinda”) Note: you cannot multiply string and string using * Only number * number or string * number is allowed MEMBERSHIP OPERATORS Membership operators (in and not in) are used to check the presence of character(s) in any string. Example Output “a” in “python” False “a” in “java” True “per” in “operators” True “men” in “membership” False “Man” in “manipulation” False “Pre” not in “presence” True COMPARISON OPERATORS (==, !=, >, <, >=,<=) used on string. Comparison will be character by character. str1=”program” str2=”python” str3=”Python” Comparison of string will be based on ASCII code of the characters. String Slicing:- Means a process of extracting part of string. Finding the Ordinal or Unicode value of a character: Function Description ord(<character>) Returns ordinal value of a character chr(<value>) Returns the corresponding character Example: >>> ord('b') Return 98 >>> chr(65) Return 'A' Slice operator with Strings: The slice operator slices a string using a range of indices. Syntax: string-name[start:end] where start and end are integer indices. It returns a string from the index start to end -1 0 1 2 3 4 5 6 7 8 9 10 11 12 13 d a t a s t r u c t u r e -14 -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1 Example: >>> str="data structure" Expression Output str[0:14] 'data structure' str[0:6] 'data s' >>> str[2:7] 'ta st'
>>> str[-13:-6] 'ata str'
>>> str[-5:-11] ' ' #returns empty string
>>> str[:14] # Missing index before colon is considered as 0. 'data structure' >>> str[0:] # Missing index after colon is considered as 14. (length of string) 'data structure' >>> str[7:] 'ructure' >>> str[4:]+str[:4] ' structuredata' >>> str[:4]+str[4:] #for any index str[:n]+str[n:] returns original string 'data structure' >>> str[8:]+str[:8] 'ucturedata str' >>> str[8:], str[:8] ('ucture', 'data str')
Built-in functions of string:
Example: str=”data structure” s1= “hello365” s2= “python” s3 = „4567‟ s4 = „ „ s5= „comp34%@‟ S No. Function Description Example 1 len( ) Returns the length of a string >>>print(len(str)) 14 2 capitalize( ) Returns a string with its first >>> str.capitalize() character capitalized. 'Data structure' 3 find(sub,sta Returns the lowest index in the >>> str.find("ruct",5,13) rt,end) string where the substring sub is 7 found within the slice range. >>> str.find("ruct",8,13) Returns -1 if sub is not found. -1 4 isalnum( ) Returns True if the characters in >>>s1.isalnum( ) the string are alphabets or True numbers. False otherwise >>>s2.isalnum( ) True >>>s3.isalnum( ) True >>>s4.isalnum( ) False >>>s5.isalnum( ) False 5 isalpha( ) Returns True if all characters in the >>>s1.isalpha( ) string are alphabetic. False False otherwise. >>>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 are digits. Otherwise False 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 are lowercase. 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 are uppercase. False False otherwise. >>> s2.isupper() False >>> s3.isupper() False >>> s4.isupper() False >>> s5.isupper() False 9 isspace( ) Returns True if there are only >>> " ".isspace() whitespace characters in the string. True False otherwise >>> "".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 the >>> str="data structure" leading characters. (Left side). >>> str.lstrip('dat') if used without any argument, it ' structure' removes the leading 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') trailing characters. (Right side). 'data struct' if used without any argument, it >>> str.rstrip('rut') removes the trailing whitespaces. 'data structure' >>> str.rstrip('tucers') 'data ' 14 split() breaks a string into words and >>> str="Data Structure" creates a list out of it >>> str.split( ) ['Data', 'Structure']