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

String Stringmethod

Uploaded by

Actor shorts
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)
13 views

String Stringmethod

Uploaded by

Actor shorts
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/ 6

Multi value /collection data type

Sunday, October 08, 2023 11:22 AM

STRING:
A String is a sequence of characters enclosed within single quotes or double quotes or three single quotes/three double quote s.
Syntax to create the string:
Variable_name = 'collection_of_characters' OR
Variable_name = "collection_of_characters" OR
Variable1_name = '''collection_of_characters''' / """collection_of_characters"""

Ex: word='hello world'


word="hello world"
message = '''this is a multiline string
hello world welcome to python programming
language
this is a new line'''

• If string is created b/w 3 pair of single quote is called as doc string/paragraph string.
• If string is started with single quote then we need to end with single quote itself and same for other two.
• If single quote (')is present in a string then " " has to be used.
Ex: 'welcome to python's world' error
"welcome to python's world"
• We have len() built in function to find the length of the collection or object or variable or string.

Raw string:
• Python raw string are the string are the string literals prefixed with "r" or "R"
• Raw string do not treat backslashes as a part of an escape sequence. If will be printed normally as a string

Regular v/s Raw string


• Regular string :consider backslash as a special sequence.
Ex: s = "Hello \task from pytho\n world"
o/p: Hello ask from pytho
world
• Raw string: consider entire string as character set irrespective of any special sequences.
Ex: s = r"Hello \task from pytho\n world"
o/p: "Hello \task from pytho\n world"

Memory Allocation In String


RAM
STACK HEAP
a = 'hello'
b = 'hi'

MAIN FRAME

0x31 0x62 0x48 0x48 0x12


a

b
0x31 0x34

• The memory allocation in string takes place in random access memory(RAM)


• Inside a RAM, there will be a two type of memory :stack and heap
• Inside a stack memory variables will get stored in a systematic way.
• Inside a heap memory the character will get stored randomly
• As string is a collection of character it has been spited into each character in the heap memory and it will have a memory bl ock which will be
pointing by the variable ,each characters of string will allocate the
• respective memory blocks and forms the string. Here the character in the heap memory are not duplicated.
• This is how memory management happens in string

New Section 1 Page 1


Indexing a string:
• A process of extracting single character at a time.
• Indexing can be positive(starts with 0)or negative(starts with -1)
• +ve : whenever we want to traverse from left to right of collection we will make use of +ve indexing. It starts from 0 till l ength of the
collection-1
• -ve : whenever we want to traverse from right to left of collection we will make use of -ve indexing. It starts from 1 till -length of the collection.
• Syntax : var_name[index]
Ex: message = 'Hello world'
+ve index
0 1 2 3 4 5 6 7 8 9 10
H e l l o w o r l d -ve index
-11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
message[6] 'w'
message[4] o
message[-6] ' '
message[-3] 'r'
• Whenever we want to access individual data item with the help of -ve index into +ve index.
+ve index = length of collection +(-ve index)
• String (str) not allow the user to modify its original values we can it as immutable collection.

Slicing a string:
• Process of extracting multiple characters at a time /simultaneously.
• Syntax : var_name[start index : end index : step value]
Start index : default value (o)[optional]
End index : default value (-length of the string)[optional]
Step value : default value (1)[optional]
• Note : Element at the end index will not be added in the slicing.
Ex :
message = 'Hello world'
0 1 2 3 4 5 6 7 8 9 10
H e l l o w o r l d
-11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
message[:5] 'Hello'
message[6:] 'world'
message[0:-6] 'Hello'
message[2:-3] 'llo wo'
message[-9:-3] 'llo wo'
message[::2] 'Hlowrd'
message[::-2] 'drwolh'
message[::-1] 'dlrow olleh'

String formatting :
• Infusing data dynamically into a string during the time of execution or runtime is called formatting.
• There are 3 ways of string formatting:
• Formatting with placeholders.
• Formatting with .format() string method
• Formatting with string literals called f-string

1. Formatting with .format() string method :


• Formatting is done by calling .format() method
• Here placeholder {} are used to infuse the data at the runtime
Ex:
greet = 'hi my name is {} and I am {} years old ' .format('Steve',25) o/p : 'hi my name is Steve and I am 25 years old'
greet = 'hi my name is {} and I am {} years old ' .format(25,'Steve') o/p : 'hi my name is 25 and I am Steve years old'
greet = 'hi my name is {} and I am {} years old ' .format(25) Error
Data = 'hi my name is {0} and I am {1} year old' .format('alex',30) o/p : 'hi my name is alex and I am 30 year old
Data = 'hi my name is {1} and I am {0} year old' .format('alex',30) o/p : 'hi my name is 30 and I am alex year old
greet = 'hi my name is {name} and I am {age} years old ' .format(name = 'Steve', age = 25) o/p : 'hi my name is Steve and I am 25 years old'

2. Formatting with string literals (f-string) :


• Here we can use outside variables directly into the string instead of passing them as arguments.

New Section 1 Page 2


• Here we can use outside variables directly into the string instead of passing them as arguments.
• Here placeholders ({variable} ) are used to infuse the data at the runtime.
Ex :
1. a = 24
b = "day"
msg = f" There are {a} hours in a {b}“ "There are 24 hours in a day"
string=f" One {b} has {a* 60} minutes“ "One day has 1440 minutes"

New Section 1 Page 3


String methods
10 October 2023 18:04

capitalize () : python strings capitalize () function returns the first letter of the string in the capital form.
Ex : my_message = 'good morning'
my_message.capitalize() 'Good morning'

upper () : python string upper () returns all the alphabet characters to uppercase.(we can have numbers and special character in string).
Ex : my_message = 'good morning'
my_message.upper() 'GOOD MORNING'

lower () : python string lower () returns all the alphabet characters to lowercase.(we can have numbers and special character in string).
Ex : my_message = 'Good Morning'
my_message.lower() 'good morning'

swapcase () : python string Swapcase () returns new string which convert uppercase to lowercase and vice-versa.
Ex : my_message = 'Good Morning'
my_message.swapcase() gOOD mORNING
count () : python string count () returns the number of occurrence of the specific substring inside the given string.
Ex : my_message = 'good morning'
my_message.count('n') 2
my_message = "Hello world, Hello universe"
print(my_message.count(‘l’)) 5 # Prints number of occurrences of the letter ‘l’
print(my_message.count('Hello', 0, 1 # Prints number of occurrences of the word 'Hello' between the indices 0 and
10)) 10

index () : python string index () returns the lowest index where the specified substring is found. OR
•Searches the string for a specified value and returns the position of where it was found
•finds the first occurrence of the specified value.
•returns valueError if the value is not found.
•Syntax:
Syntax : str.index('substring',[startindex],[ endindex])
rindex() : Searches the string for a specified value and returns the last position of where it was found
Eg : my_message = "Hello World"
1. print(my_message.index('l’)) 2 # Prints the index of first occurence of the letter 'I'
2. print(my_message.rindex("l’)) 9 # Prints the index of last occurence of the letter’l’
3. print(my_message.index('Universe’)) ValueError
my_message = 'good morning'
my_message.index('m') 5

find () : python string find () is used to find the index of a substring in a string. OR
• Searches the string for a specified value and returns the position of where it was found
• finds the first occurrence of the specified value.
• returns -1 if the value is not found.
• Syntax: string.find(value, [start], [end])
rfind() : Searches the string for a specified value and returns the last position of where it was found
Eg : my_message = "Hello World"
1. print(my_message.find('I’)) 2 # Prints the index of first occurence of the letter 'I’
2. print(my_message.rfind('I’)) 9 # Prints the index of last occurence of the letter 'I'
3. print(my_message.find('Universe’)) -1
4. print("today is beautiful day".rfind("day")) 19
5. print("today is beautiful day".find("day")) 2

replace () : python string replace () is used to create a new string by replacing some parts of another string. OR
• Replaces a specified phrase with another specified phrase.
• Syntax: string.replace(oldvalue, newvalue, [count])
Eg:
"Malayalam".replace("a", "q") "Mqlqyqlqm"
"Hello World".replace("World", "Universe") "Hello Universe“

New Section 1 Page 4


"Malayalam".replace("a", "q", 1) "Mqlayalam"

startswith () : python strings Startswith () function returns True if the string starts with the given specified value, otherwise it returns
False.
• Syntax: string.startswith(value, [start], [end])
Eg:
"how are you".startswith("are") False

endswith () : python strings endswith () function returns True if the string ends with the given specified value, otherwise it returns False.
• Syntax: string.endswith(value, [start], [end])
Eg:
"how are you".endswith("you") True

split () : python string split () is used to split a string into list of string based on the delimiter. OR
• Splits the string at the specified separator, and returns a list.
• syntax: string.split([separator], [maxsplit])
rsplit() method splits a string into a list, starting from the right.
• If no "max" is specified, this method will return the same as the split().
• Converts a string into a list.
Eg:
'This is my string'.split('s’) ['Thi', 'i', ' my', 'tring']
"This is my string".split() ['This', 'is', 'my', 'string']
"This is my string".split(" ",2) ['This', 'is', 'my string']
"This is my string".rsplit(" ",2) ['This is', 'my', 'string]

join() : Joins the elements of an sequence using the string specified. OR Syntax: string.join(iterable)
• Converting other data type into a string.
Eg : data = "hai"
data.join(["hello", "world"]) "hellohaiworld"
message = 'hello'
'-'.join(message) "h-e-l-l-o“ # Joins each character of the string using '-'
','.join(message) “h,e,l,l,o” # Joins each character of the string using ','

strip() : removes any leading (spaces at the beginning) and trailing (spaces at the end) characters (space is the default leading character to
remove)
Syntax: string.strip()
rstrip():removes any trailing characters
Syntax: string.rstrip ()
lstrip():A removes any leading characters
Syntax: string.Istrip()

isalnum() : Returns True if all characters in the string are alphanumeric


isalpha() : Returns True if all characters in the string are in the alphabet
isdigit() : Returns True if all characters in the string are digits
islower() : Returns True if all alphabets in the string are lower case
isupper() : Returns True if all alphabets in the string are upper case
isspace() : Returns True if all characters in the string are spaces.

Note: All string methods returns new values. They do not change the original string.

METHODS ARGUMENT RETURN TYPE


capitalize () String
upper () String
lower() String
swapcase() String
count() (substr,[SI],[EI]) integer
find(),rfind() (substr,[SI],[EI]) integer
index(),rindex() (substr,[SI],[EI]) integer
replace() (old_str,new_str,[count]) String
split(),rsplit() ([seperator],[max.split]) list
join() (iterable) String

New Section 1 Page 5


join() (iterable) String
strip(),lstrip(),rstrip() String
startwith(),endwith() (substr,[SI],[EI]) bool
isupper() bool
islower() bool
isdigit() bool
isalnum() bool
isalpha() bool
isspace() bool
isidentifier() bool

Concatenation :
It is the process of combination two or more strings by using plus(+) operator.
Syntax : str1 + str2
Ex : s1 = 'hello'
s2 = 'world'
Print(s1+s2) 'helloworld'
a = 'hai'
b = 'hello'
c = 'good'
d= 'morning'
Print(a+b+c+d) 'haihellogoodmorning
Print(a+' '+b+' '+c+' '+d) 'hai hello good morning

Replication :
It is a process of creating some copies of given string using asterisk(*) operator.
It returns specified number of duplicate specified strings.
Syntax : str * int
Ex : s = 'hello'
s*5 'hellohellohellohellohello
S = '67'
s*4 '67676767'

New Section 1 Page 6

You might also like