Documente Academic
Documente Profesional
Documente Cultură
Strings
Strings - Introduction
• A string is a sequence of characters treated as a
single unit
• A character is simply a symbol
• String is an object of the str class
Creating a string
Using constructor of the string class – Method 1
S1=str() #Creating a string
creates empty string
S2=str(“Welcome”) # creates string object for welcome
Method 2:
S1=“ “
S2=“welcome”
Creating a string
# all of the following are equivalent
my_string = 'Hello‘
print(my_string)
my_string = "Hello“
print(my_string)
my_string = '''Hello''‘
print(my_string)
# triple quotes string can extend multiple lines
my_string = """Hello, welcome to
the world of Python""“
print(my_string)
How to access characters in a string?
• Individual characters in a string can be accessed
using index[] operator and a range of characters
using slicing(:)operation.
• Index starts from 0.
• The index must be an integer
• Trying to access a character out of index range will
raise an IndexError.
• Python allows negative indexing for its sequences.
• The index of -1 refers to the last item, -2 to the
second last item and so on
How to change a string?
• Strings are immutable. This means that elements of
a string cannot be changed once it has been
assigned.
• We can simply reassign different strings to the
same name.
How to delete a string?
• We cannot delete or remove characters from a
string.
• But deleting the string entirely is possible using the
keyword del.
String operators
• Slicing
• Concatenation (+)
• Repetition (*)
• Membership - in and not in
Slicing
• Used to obtain the substring of the string
• Slice by two indices (start,end)
Syntax
String_name[start_index: End_index: step_size]
Example
str = 'programmes‘
#slicing 2nd to 5th character
print('str[1:5] = ', str[1:5])
#slicing 6th to 2nd last character
print('str[5:-2] = ', str[5:-2])
Slicing with step size
>>> my_string="welcome"
>>> print(my_string[0::2])
wloe
+ operator
Used to join two strings
>>> s1="welcome "
>>> s2="to kct"
>>> s1+s2
'welcome to kct'
* operator
• Used to concatenate the same string multiple times
• Repetition operator
>>> s1*3
'welcome welcome welcome '
>>>
in and not in operator
Used to check whether a string is present in another
string
>>> s1="Kumaraguru college of technology"
>>> "college" in s1
True
>>> "engineering" in s1
False
>>> "engineering" not in s1
True
Iterating Through String - for loop
s="Bio Technology"
for character in s:
print(character, end="")
Output:
Bio Technology
s="Bio Technology"
for index in range(0,len(s)):
print(s[index],end="")
Iterating Through String- while loop
s="Bio Technology"
index=0
while(index <len(s)):
print(s[index],end="")
index=index+1
Strings and Character Numbers
• The ord function returns the numeric (ordinal) code of
a single character.
• The chr function converts a numeric code to the
corresponding character.
>>> ord("A")
65
>>> ord("a")
97
>>> chr(97)
'a'
>>> chr(65)
'A'
Determine if str occurs in string, or in a substring of string if starting index beg and
ending index end are given; returns index if found and -1 otherwise
8 index(str, beg=0, end=len(string))
9 isa1num()
Returns true if string has at least 1 character and all characters are alphanumeric
and false otherwise
10 isalpha()
Returns true if string has at least 1 character and all characters are alphabetic and
false otherwise
11 isdigit()
12 islower()
Returns true if string has at least 1 cased character and all cased characters are in
lowercase and false otherwise
13 isnumeric()
Returns true if a unicode string contains only numeric characters and false otherwise
14 isspace()
Returns true if string contains only whitespace characters and false otherwise
15 istitle()
Returns true if string is properly "titlecased" and false otherwise
16 isupper()
Returns true if string has at least one cased character and all cased characters are in
uppercase and false otherwise
17 join(seq)
Merges (concatenates) the string representations of elements in sequence seq into a
string, with separator string
18 len(string)
Returns the length of the string
19 ljust(width[, fillchar])
Returns a space-padded string with the original string left-justified to a total of width
columns
20 lower()
Converts all uppercase letters in string to lowercase
21 lstrip()
Removes all leading whitespace in string
22 maketrans()
Returns a translation table to be used in translate function.
23 max(str)
Returns the max alphabetical character from the string str
24 min(str)
Replaces all occurrences of old in string with new, or at most max occurrences if max
given
26 rfind(str, beg=0,end=len(string))
28 rjust(width,[, fillchar])
30 split(str="", num=string.count(str))
Splits string according to delimiter str (space if not provided) and returns list of
substrings; split into at most num substrings if given
31 splitlines( num=string.count('\n'))
Splits string at all (or num) NEWLINEs and returns a list of each line with NEWLINEs
removed
32 startswith(str, beg=0,end=len(string))
Determines if string or a substring of string (if starting index beg and ending index
end are given) starts with substring str; Returns true if so, and false otherwise
33 strip([chars])
34 swapcase()
35 title()
Returns "titlecased" version of string, that is, all words begin with uppercase, and the
rest are lowercase
36 translate(table, deletechars="")
Translates string according to translation table str(256 chars), removing those in the
del string
37 upper()
38 zfill (width)
Returns original string leftpadded with zeros to a total of width characters; intended
for numbers, zfill() retains any sign given (less one zero)
39 isdecimal()
Returns true if a unicode string contains only decimal characters and false otherwise