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

string 1

Uploaded by

Saket Pentapati
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

string 1

Uploaded by

Saket Pentapati
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 32

CSE1012-Python

L.Pavithra
Assistant Professor
SCOPE
VIT AP

11/10/2022 CSE1001 - Problem Solving and Programmi 1


ng
Python STRING concepts
-continue

11/10/2022 CSE1001 - Problem Solving and Programmi 2


ng
Application of built-in function Chr
() and Ord ()
• The Chr () function is a built function that
takes a single argument as input. The function
takes Unicode characters as an input which
ranges from 0 to 1,114 and 111, respectively.

• Syntax: –
Chr(Unicode character)

11/10/2022 CSE1001 - Problem Solving and Programmi 3


ng
11/10/2022 CSE1001 - Problem Solving and Programmi 4
ng
• Python Code1:
print("Unicode character of the tab is")
Ord=ord('\t')
print(Ord)
• Output:
Unicode character of the tab is 9

• Python Code2:
TextExample=“Welcome+chr(9)+CSE1001“
print(TextExample)
• Output:
11/10/2022 CSE1001 - Problem Solving and Programmi 5
ng
String methods
• In Python, a method is a function that is
defined with respect to a particular object.
• The syntax is
<object>.<method>(<parameters>)

>>> dna = “ACGT”


>>> dna.find(“T”)
3
11/10/2022 CSE1001 - Problem Solving and Programmi 6
ng
String methods
>>> "GATTACA".find("ATT")
1
>>> "GATTACA".count("T")
2
>>> "GATTACA".lower()
'gattaca'
>>> "gattaca".upper()
'GATTACA'
>>> "GATTACA".replace("G", "U")
'UATTACA‘
>>> "GATTACA".replace("C", "U")
'GATTAUA'
>>> "GATTACA".replace("AT", "**")
'G**TACA'
>>> "GATTACA".startswith("G")
True
>>> "GATTACA".startswith("g")
False

11/10/2022 CSE1001 - Problem Solving and Programmi 7


ng
Strings are immutable
• Strings cannot be modified; instead, create a new
one.
>>> s = "GATTACA"
>>> s[3] = "C"
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: object doesn't support item assignment
>>> s = s[:3] + "C" + s[4:]
>>> s
'GATCACA'
>>> s = s.replace("G","U")
>>> s
'UATCACA'

11/10/2022 CSE1001 - Problem Solving and Programmi 8


ng
Strings are immutable
• String methods do not modify the string; they
return a new string.
>>> sequence = “ACGT”
>>> sequence.replace(“A”, “G”)
‘GCGT’
>>> print (sequence)
ACGT

>>> sequence = “ACGT”


>>> new_sequence = sequence.replace(“A”, “G”)
>>> print (new_sequence)
GCGT
11/10/2022 CSE1001 - Problem Solving and Programmi 9
ng
String summary
Basic string operations:
S = "AATTGG" # assignment - or use single quotes ' '
s1 + s2 # concatenate
s2 * 3 # repeat string
s2[i] # index character at position 'i'
s2[x:y] # index a substring
len(S) # get length of string
int(S) # or use float(S) # turn a string into an integer or floating point decimal

Methods:
S.upper()
S.lower()
S.count(substring)
S.replace(old,new)
S.find(substring)
S.startswith(substring), S. endswith(substring)

Printing:
print var1,var2,var3 # print multiple variables
print "text",var1,"text" # print a combination of explicit text (strings) and variables

11/10/2022 CSE1001 - Problem Solving and Programmi 10


ng
String Methods
Method Description

Returns the copy of the string with its first character


str.capitalize() capitalized and the rest of the letters are in lowercased.

Returns a lowered case string. It is similar to the lower()


method, but the casefold() method converts more characters
string.casefold() into lower case.

Returns a new centered string of the specified length, which is


padded with the specified character. The deafult character is
string.center() space.

Searches (case-sensitive) the specified substring in the given


string and returns an integer indicating occurrences of the
string.count() substring.
11/10/2022 CSE1001 - Problem Solving and Programmi 11
ng
Method Description

Returns True if a string ends with the specified suffix (case-


string.endswith() sensitive), otherwise returns False.

Returns a string with all tab characters \t replaced with one or


more space, depending on the number of characters before \t
string.expandtabs() and the specified tab size.
Returns the index of the first occurence of a substring in the
given string (case-sensitive). If the substring is not found it
string.find() returns -1.

Returns the index of the first occurence of a substring in the


string.index() given string.

Returns True if all characters in the string are alphanumeric


string.isalnum() (either alphabets or numbers). If not, it returns False.

Returns True if all characters in a string are alphabetic (both


lowercase and uppercase) and returns False if at least one
string.isalpha() character is not an alphabet.
11/10/2022 CSE1001 - Problem Solving and Programmi 12
ng
Method Description

Returns True if the string is empty or all characters in the string


string.isascii() are ASCII.

Returns True if all characters in a string are decimal characters.


string.isdecimal() If not, it returns False.
Returns True if all characters in a string are digits or Unicode
string.isdigit() char of a digit. If not, it returns False.
Checks whether a string is valid identifier string or not. It
returns True if the string is a valid identifier otherwise returns
string.isidentifier() False.
Checks whether all the characters of a given string are
lowercased or not. It returns True if all characters are
string.islower() lowercased and False even if one character is uppercase.
Checks whether all the characters of the string are numeric
characters or not. It will return True if all characters are
numeric and will return False even if one character is non-
string.isnumeric() numeric.
11/10/2022 CSE1001 - Problem Solving and Programmi 13
ng
Method Description

Returns True if all the characters of the given string are


Printable. It returns False even if one character is Non-
string.isprintable() Printable.
Returns True if all the characters of the given string are
whitespaces. It returns False even if one character is not
string.isspace() whitespace.
Checks whether each word's first character is upper case and
the rest are in lower case or not. It returns True if a string is
titlecased; otherwise, it returns False. The symbols and
string.istitle() numbers are ignored.
Returns True if all characters are uppercase and False even if
string.isupper() one character is not in uppercase.
Returns a string, which is the concatenation of the string (on
which it is called) with the string elements of the specified
string.join() iterable as an argument.
Returns the left justified string with the specified width. If the
specified width is more than the string length, then the string's
string.ljust()
11/10/2022
remaining part is filled with the specified fillchar.
CSE1001 - Problem Solving and Programmi 14
ng
Method Description

Returns the copy of the original string wherein all the


string.lower() characters are converted to lowercase.

Returns a copy of the string by removing leading characters


string.lstrip() specified as an argument.
Returns a mapping table that maps each character in the given
string to the character in the second string at the same position.
This mapping table is used with the translate() method, which
string.maketrans() will replace characters as per the mapping table.
Splits the string at the first occurrence of the specified string
separator sep argument and returns a tuple containing three
elements, the part before the separator, the separator itself, and
string.partition() the part after the separator.
Returns a copy of the string where all occurrences of a
string.replace() substring are replaced with another substring.

Returns the highest index of the specified substring (the last


string.rfind()
11/10/2022 occurrence
CSE1001 -of
ng
theSolving
Problem substring) in the given string.
and Programmi 15
Method Description

Returns the index of the last occurence of a substring in the


string.rindex() given string.
Returns the right justified string with the specified width. If the
specified width is more than the string length, then the string's
string.rjust() remaining part is filled with the specified fill char.
Splits the string at the last occurrence of the specified string
separator sep argument and returns a tuple containing three
elements, the part before the separator, the separator itself, and
string.rpartition() the part after the separator.
Splits a string from the specified separator and returns a list
string.rsplit() object with string elements.
Returns a copy of the string by removing the trailing characters
string.rstrip() specified as argument.

Splits the string from the specified separator and returns a list
string.split() object with string elements.
11/10/2022 CSE1001 - Problem Solving and Programmi 16
ng
Method Description

Splits the string at line boundaries and returns a list of lines in


string.splitlines() the string.

Returns True if a string starts with the specified prefix. If not, it


string.startswith() returns False.
Returns a copy of the string by removing both the leading and
string.strip() the trailing characters.
Returns a copy of the string with uppercase characters
converted to lowercase and vice versa. Symbols and letters are
string.swapcase() ignored.
Returns a string where each word starts with an uppercase
string.title() character, and the remaining characters are lowercase.

Returns a string where each character is mapped to its


string.translate() corresponding character in the translation table.

11/10/2022 CSE1001 - Problem Solving and Programmi 17


ng
Method Description

Returns a string in the upper case. Symbols and numbers


string.upper() remain unaffected.

Returns a copy of the string with '0' characters padded to the


left. It adds zeros (0) at the beginning of the string until the
string.zfill() length of a string equals the specified width parameter.

11/10/2022 CSE1001 - Problem Solving and Programmi 18


ng
To check if all letters in a
String are in Uppercase
• isupper() function is used to check if all letters in a string are
in upper case
• Example
>>> 'a'.isupper()
False
>>> 'A'.isupper()
True
>>> 'AB'.isupper()
True
>>> 'ABc'.isupper()
False
11/10/2022 CSE1001 - Problem Solving and Programmi 19
ng
To check if all letters in a
String are in Lowercase
• isupper() function is used to check if all letters
in a string are in upper case
• Example
>>> 'a'.islower()
True
>>> 'aB'.islower()
False

11/10/2022 CSE1001 - Problem Solving and Programmi 20


ng
To check if a sentence is in
Title case
• isupper() function is used to check if all letters
in a string are in upper case
• Example
>>> 'Apple Is A Tree'.istitle()
True
>>> 'Apple Is A tree'.istitle()
False

11/10/2022 CSE1001 - Problem Solving and Programmi 21


ng
list of complete set of symbols
Format Symbol Conversion
%c character

%s string conversion via str() prior to formatting


%i signed decimal integer
%d signed decimal integer
%u unsigned decimal integer
%o octal integer
%x hexadecimal integer (lowercase letters)

%X hexadecimal integer (UPPERcase letters)

%e exponential notation (with lowercase 'e')

%E exponential notation (with UPPERcase 'E')


%f floating point real number
%g the shorter of %f and %e
11/10/2022 %G the shorter of %fSolving
CSE1001 - Problem andand%E
Programmi 22
ng
Other supported symbols and
functionality
Symbol Functionality
* argument specifies width or precision
- left justification
+ display the sign
<sp> leave a blank space before a positive number
add the octal leading zero ( '0' ) or hexadecimal leading '0x' or '0X',
# depending on whether 'x' or 'X' were used.
0 pad from left with zeros (instead of spaces)
% '%%' leaves you with a single literal '%'
(var) mapping variable (dictionary arguments)
m is the minimum total width and n is the number of digits to
m.n. display after the decimal point (if appl.)

11/10/2022 CSE1001 - Problem Solving and Programmi 23


ng
Sample problem #1
• Write a program called dna2rna.py that reads a DNA sequence
from the first command line argument, and then prints it as an
RNA sequence. Make sure it works for both uppercase and
lowercase input.

> python dna2rna.py AGTCAGT


ACUCAGU First get it working
> python dna2rna.py actcagt just for uppercase
letters.
acucagu
> python dna2rna.py ACTCagt
ACUCagu

11/10/2022 CSE1001 - Problem Solving and Programmi 24


ng
Two solutions
import sys
sequence = sys.argv[1]
new_sequence = sequence.replace(“T”, “U”)
newer_sequence = new_sequence.replace(“t”, “u”)
print newer_sequence

import sys
print sys.argv[1]

11/10/2022 CSE1001 - Problem Solving and Programmi 25


ng
Two solutions
import sys
sequence = sys.argv[1]
new_sequence = sequence.replace(“T”, “U”)
newer_sequence = new_sequence.replace(“t”, “u”)
print newer_sequence

import sys
print sys.argv[1].replace(“T”, “U”)

11/10/2022 CSE1001 - Problem Solving and Programmi 26


ng
Two solutions
import sys
sequence = sys.argv[1]
new_sequence = sequence.replace(“T”, “U”)
newer_sequence = new_sequence.replace(“t”, “u”)
print newer_sequence

import sys
print sys.argv[1].replace(“T”, “U”).replace(“t”, “u”)

• It is legal (but not always desirable) to chain together


multiple methods on a single line.

11/10/2022 CSE1001 - Problem Solving and Programmi 27


ng
Sample problem #2
• Write a program get-codons.py that reads the
first command line argument as a DNA
sequence and prints the first three codons, one
per line, in uppercase letters.
> python get-codons.py TTGCAGTCG
TTG
CAG
TCG
> python get-codons.py TTGCAGTCGATC
TTG
CAG
TCG
> python get-codons.py tcgatcgac
TCG
ATC
GAC

11/10/2022 CSE1001 - Problem Solving and Programmi 28


ng
Solution #2
import sys
sequence = sys.argv[1]
upper_sequence = sequence.upper()
print upper_sequence[:3]
print upper_sequence[3:6]
print upper_sequence[6:9]

11/10/2022 CSE1001 - Problem Solving and Programmi 29


ng
Sample problem #3 (optional)
• Write a program that reads a protein
sequence as a command line argument and
prints the location of the first cysteine residue.
> python find-cysteine.py
MNDLSGKTVIITGGARGLGAEAARQAVAAGARVVLADVLDEEGAATARELGDAARYQHLDVTI
EEDWQRVCAYAREEFGSVDGL 70
> python find-cysteine.py
MNDLSGKTVIITGGARGLGAEAARQAVAAGARVVLADVLDEEGAATARELGDAARYQHLDVTI
EEDWQRVVAYAREEFGSVDGL -1

11/10/2022 CSE1001 - Problem Solving and Programmi 30


ng
Solution #3
import sys
protein = sys.argv[1]
upper_protein = protein.upper()
print upper_protein.find(“C”)

11/10/2022 CSE1001 - Problem Solving and Programmi 31


ng
11/10/2022 CSE1001 - Problem Solving and Programmi 32
ng

You might also like