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

strings

The document provides an overview of Python strings, explaining their characteristics, indexing methods, and various operations such as concatenation, slicing, and membership testing. It also details built-in string methods for counting, checking prefixes/suffixes, case conversion, and more. Additionally, it highlights that strings are immutable, meaning their individual characters cannot be modified or deleted directly.

Uploaded by

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

strings

The document provides an overview of Python strings, explaining their characteristics, indexing methods, and various operations such as concatenation, slicing, and membership testing. It also details built-in string methods for counting, checking prefixes/suffixes, case conversion, and more. Additionally, it highlights that strings are immutable, meaning their individual characters cannot be modified or deleted directly.

Uploaded by

bioresearchpcod
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

Python String

• A string is a sequence of characters.

>> fruit = 'banana'


>> letter = fruit[0]
>> print letter
b

You can access the characters one at a time with the bracket
operator

The second statement extracts the character at index position 0


from the fruit variable and assigns it to letter variable.

The expression in brackets is called an index. The index


indicates which character in the sequence you want (hence the
name).
Accessing Python Strings
• In Python, Strings are stored as individual characters in a
contiguous memory location.

• The benefit of using String is that it can be accessed from


both the directions (forward and backward).
– Forward indexing starts with 0,1,2,3,....
– Backward indexing starts with -1,-2,-3,-4,....

str[0]='P'=str[-6],
str[1]='Y' = str[-5],
str[2] = 'T' = str[-4],
str[3] = 'H' = str[-3],
str[4] = 'O' = str[-2],
str[5] = 'N' = str[-1].
• 'str' object does not support item assignment

• We cannot delete or remove characters from a string.


But deleting the string entirely is possible using the
keyword del.

>>> del my_string[1]


TypeError: 'str' object doesn't support item deletion

>>> del my_string


>>> my_string
NameError: name 'my_string' is not defined
>> letter = fruit[1.5]
Type Error: string indices must be integers

empty string, represented by two quotation


marks:
Strings Operators
Operator Description Example
+ Concatenation - Adds values on either side of the a + b will give HelloPython
operator
* Repetition - Creates new strings, concatenating a*2 will give -HelloHello
multiple copies of the same string

[] Slice - Gives the character from the given index a[1] will give e

[:] Range Slice - Gives the characters from the given a[1:4] will give ell
range
in Membership - Returns true if a character exists in H in a will give True
the given string
not in Membership - Returns true if a character does not H not in a will give False
exist in the given string

% Format - Performs String formatting


print "My name is %s and weight is %d kg!" % ('Zara', 21)
will give
My name is Zara and weight is 21 kg!
• A segment of a string is called a slice.
• If we want to access a range, we need the index
that will slice the portion from the string.

Syntax: variable [n:m]

It returns the part of the string from the "n-eth"


character to the "m-eth" character, including the first
but excluding the last.
>> fruit = 'banana' >> s = 'Monty Python‘
>> fruit[:3] >> print s[0:5]
'ban' Monty
>> fruit[3:]
'ana'

>> greeting = 'Hello, world!'


>> new_greeting = 'J' + greeting[1:]
>> print new_greeting
Jello, world!
count(string,begin,end) It Counts number of msg="welcome";
times substring occurs in substr1="o";
a String between begin print(msg.count(substr1,4,16))
and end index. print(msg.count("t"))

1
0

endswith(suffix It returns a Boolean value string1="Welcome"


,begin=0,end=n) if the string terminates print(string1.endswith("me"))
with given suffix
between begin and end. True

startswith(str It returns a Boolean value string1="Hello Python"


,begin=0,end=n) if the string starts with print(string1.startswith('Hello')
given str between begin )
and end.
True
len(string) It returns the length of a string="WELCOME"
string. print(len(string))

lower() It converts all the string="WELCOME"


characters of a string to print(string.lower())
Lower case.

welcome

upper() It converts all the string="welcome"


characters of a string to print(string.upper())
Upper Case.
WELCOME

capitalize() It capitalizes the first >>> 'abc'.capitalize()


character of the String.
'Abc'
find(substring It returns the index value str="Welcome"
,beginIndex, endIndex) of the string where print(str.find("come"))
substring is found
between begin index and 3
end index.

index(subsring, It throws an exception if str="Welcome"


beginIndex, endIndex) string is not found and print(str.index("come"))
works same as find()
method. 3

isalnum() It returns True if str1="Python47"


characters in the string are print(str1.isalnum())
alphanumeric i.e.,
alphabets or numbers and True
there is at least 1
character. Otherwise it
returns False.
swapcase() It inverts case of all string1="Hello Python"
characters in a string. print(string1.swapcase())

hELLO pYTHON

join() The method join() returns >>> s="-"


a string in which the >>> s1='abc'
string elements of >>> print(s.join(s1))
sequence have been a-b-c
joined by str separator.

strip([chars]) Performs both lstrip() and str ="00this is string00"


rstrip() on string. print(str.strip('0'))

this is string
Thanks

You might also like