[go: up one dir, main page]

0% found this document useful (0 votes)
18 views10 pages

9 Strings Chap 5

9 Strings Chap 5 cs

Uploaded by

sd5703261
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)
18 views10 pages

9 Strings Chap 5

9 Strings Chap 5 cs

Uploaded by

sd5703261
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/ 10

STRINGS

>>> s = "GATTACA"
0 1 2 3 4 5 6
s G A T T A C A
-7 -6 -5 -4 -3 -2 -1

>>> s = "GATTACA"
>>> s[0] 0 1 2 3 4 5 6
'G'
>>> s[1] G A T T A C A
'A'
>>> s[-1] -7 -6 -5 -4 -3 -2 -1
'A'
>>> s[-2]
'C'
>>> s[7]
Traceback (most recent call last):
File "<stdin>", line 1, in ?
IndexError: string index out of range
>>>
SLICING IN STRING
string [start : stop : step]
By default start = 0
By default stop = Last Index
By default step = 1
start, stop and step may be negative

CREATING STRINGS
Strings start and end with a single or double quote characters (they
must be the same)
"This is a string"
"This is another string"
""
"Strings can be in double quotes"
‘Or in single quotes.’
'There’s no difference.'
‘Okay, there\’s a small one.’
SOME SPECIAL CHARACTERS
Escape Sequence Meaning
\\ Backslash (keep a \)
\' Single quote (keeps the ')
\" Double quote (keeps the ")
\n Newline
\t Tab

SPECIAL CHARACTERS AND ESCAPE SEQUENCES


Backslashes (\) are used to introduce special characters
>>> s = 'Okay, there\'s a small one.'

The \ “escapes” the following single quote


>>> print s
Okay, there's a small one.
(A) String Traversal Using for Loop:
>>> str1 = 'Hello World!'
>>> for ch in str1:
print(ch,end = '')

Hello World! #output of for loop


In the above code, the loop starts from the first character of the
string str1 and automatically ends when the last character is
accessed.

(B) String Traversal Using while Loop:


>>> str1 = 'Hello World!'
>>> index = 0
#len(): a function to get length of string
>>> while index < len(str1):
print(str1[index],end = '')
index += 1
Hello World! #output of while loop
Here while loop runs till the condition index < len(str) is True,
where index varies from 0 to len(str1) -1.
STRING OPERATORS
Concatenation
>>> "GAT" + "TACA"
'GATTACA‘

Repeat/Repetition
>>> "A" * 10
'AAAAAAAAAA'

Membership
>>> "G" in "GATTACA"
True
>>> "GAT" in "GATTACA"
True
>>> "AGT" in "GATTACA"
False
STRING FUNCTIONS
>>> len(st) >>> st.startswith("HELL")
17 True
>>> st.startswith("HY")
>>> st.title() False
'Hello How Are You’
>>> st.count("O")
>>> st.capitalize() 3
'Hello how are you’
>>> st.find("OW")
>>> st.lower() 7
'hello how are you‘
>>> st.index("O")
>>> st.upper() 4
'HELLO HOW ARE YOU‘ >>> st.index("W")
8
>>> st.endswith("OU")
True >>> st.replace("U","N")
>>> st.endswith("EW") 'HELLO HOW ARE YON'
False >>> st.replace("O","**")
'HELL** H**W ARE Y**U‘
String Functions
isalnum(), isalpha(), isdigit(), islower(), isspace(),
isupper(), istitle()

Returns true if all characters in the string match the


condition such as digit etc
>>> "123456".isdigit()
True
>>> "abcd123".isdigit()
False

lstrip(), rstrip() – returns a string after removing


characters from left or right. It will remove characters also
if found in any combination.
>>> "beautiful".lstrip("bea")
'utiful'
>>> "beautiful".lstrip("bee")
'autiful'
>>> "beautiful".lstrip("eab")
'utiful'
>>> "beautiful".lstrip("ebct")
'autiful'
String Functions
join() - Returns a string in which the characters in the
string have been joined by a separator
>>> str1 = ('HelloWorld!')
>>> str2 = '-' #separator
>>> str2.join(str1)
'H-e-l-l-o-W-o-r-l-d-!‘

partition()) Partitions the given string at the first


occurrence of the substring (separator) and returns the
string partitioned into three parts.
1. Substring before the separator
2. Separator
3. Substring after the separator
If the separator is not found in the string, it returns the
whole string itself and two empty strings

>>> str1 = 'India is a Great Country'


>>> str1.partition('is')
('India ', 'is', ' a Great Country')
>>> str1.partition('are')
('India is a Great Country',' ','
String Functions
split() Returns a list of words delimited by the specified substring. If
no delimiter is given then words are separated by space.

>>> str1 = 'India is a Great Country'

>>> str1.split()
['India','is','a','Great','Country']

>>> str1 = 'India is a Great Country'


>>> str1.split('a')
['Indi', ' is ', ' Gre', 't Country']
Converting from/to strings
>>> "38" + 5
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: cannot concatenate 'str' and 'int' objects

>>> int("38") + 5
43

>>> "38" + str(5)


'385'

>>> int("38"), str(5)


(38, '5')

>>> int("2.71828")
Traceback (most recent call last):
File "<stdin>", line 1, in ?
ValueError: invalid literal for int(): 2.71828

>>> float("2.71828")
2.71828

You might also like