Strings in Python (1) - 231116 - 111357
Strings in Python (1) - 231116 - 111357
STRINGS IN PYTHON
Creating and Storing Strings: Strings are another basic data type available in Python.
They consist of one or more characters surrounded by matching quotation marks. For
example,
1. >>> single_quote = 'This is a single message'
>>> print(single_quote)
2. >>> double_quote = "Hey it is my book"
>>> print(double_quote)
3. >>> single_char_string = "A"
>>> print(single_char_string)
4. >>> empty_string = ""
>>> print(empty_string)
5. >>> empty_string = ''
>>> print(empty_string)
6. >>> single_within_double_quote = "Opportunities don't happen. You create them."
>>> print(single_within_double_quote)
7. >>> double_within_single_quote = "Why did she call the man 'smart'?"
>>> print(double_within_single_quote)
8. >>> same_quotes = 'I\'ve an idea'
>>> print(same_quotes)
9. >>> triple_quote_string = '''This
… is
… triple
… quote'''
>>> print(triple_quote_string)
10. >>> triple_quote_string
'This \n is\n triple\n quote'
Strings are surrounded by either single ➀ or double quotation marks ➁. To store a
string inside a variable, you just need to assign a string to a variable. In the above code,
all the variables on the left side of the assignment operator are string variables. A single
character is also treated as string ➂. A string does not need to have any characters in it.
Both ''➃ and "" ➄ are valid strings, called empty strings. A string enclosed in double
quotation marks can contain single quotation marks ➅. Likewise, a string enclosed in
single quotation marks can contain double quotation marks ➆. So basically, if one type
of quotation mark surrounds the string, you have to use the other type within it. If you
want to include the same quotation marks within a string as you have used to enclose
the string, then you need to preface the inner quote with a backslash ➇. If you have a
string spanning multiple lines, then it can be included within triple quotes ➈. All white
spaces and newlines used inside the triple quotes are literally reflected in the string ➉.
Strings are immutable in python. It means that the contents of the string cannot
be changed after it has been created. An attempt to do this would lead to an
error.
Each character has its index or can be accessed using its index.
String in python has two-way index for each location. (0, 1, 2, ..…….
In the forward direction and -1, -2, -3, in the backward direction.)
Example:
0 1 2 3 4 5 6 7
S i n D h i a n
-8 -7 -6 -5 -4 -3 -2 -1
The str() function: The str() function returns a string which is considered an informal
nicely printable representation of the given object. The syntax for str() function is,
str(object)
It returns a string version of the object. If the object is not provided, then it returns
an empty string.
1. >>> str(10)
'10'
2. >>> create_string = str()
3. >>> type(create_string)
Here integer type is converted to string type. Notice the single quotes to represent the
string ➀. The create_string is an empty string ➁of type str ➂.
String Operators:
a. Basic Operators (+, *)
b. Membership Operators ( in, not in)
c. Comparison Operators (==, !=, <, <=, >, >=)
a. Basic Operators: There are two basic operators of strings:
i. String concatenation Operator (+)
ii. String repetition Operator (*)
i. String concatenation Operator: The + operator creates a new string by joining the
two operand strings.
Example:
>>>”Hello”+”Python”
‘HelloPython’
>>>’2’+’7’
’27’
>>>”Python”+”3.6”
‘Python3.6’
Example:
>>>”you” * 3
‘youyouyou’
>>>3*”you”
‘youyouyou’
Note: You cannot have strings as n=both the operands with * operator.
Example:
>>>”you” * “you” # can't multiply sequence by non-int of type 'str'
It is invalid and generates an error.
b. Membership Operators:
in – Returns True if a character or a substring exists in the given string; otherwise
False
not in - Returns True if a character or a substring does not exist in the given string;
otherwise False
Example:
>>> "sin" in "Sindhian"
False
>>> "Sin" in "Sindhian"
True
c. Comparison Operators: These operators compare two strings character by
character according to their ASCII value.
‘0’ to ‘9’ 48 to 57
‘A’ to ‘Z’ 65 to 90
‘a’ to ‘z’ 97 to 122
Example:
>>> 'abc'>'abcD'
False
>>> 'ABC'<'abc'
True
>>> 'abcd'>'aBcD'
True
>>> 'aBcD'<='abCd'
True
Finding the Ordinal or Unicode value of a character:
Function Description
ord(<character>) Returns ordinal value of a character
chr(<value>) Returns the corresponding
character
Example:
For example,
1. >>> count_characters = len ("eskimos")
2. >>> count_characters
7
3. >>> max("axel")
'x'
4. >>> min("sindhian")
'a'
The number of characters in the string "eskimos" ➀ is calculated using len() function
➁. Characters with highest and lowest ASCII value are calculated using max() ➂ and
min() ➃ functions.
Accessing Characters in String by Index Number
Each character in the string occupies a position in the string. Each of the string’s
character corresponds to an index number. The first character is at index 0; the next
character is at index 1, and so on. The length of a string is the number of characters in it.
You can access each character in a string using a subscript operator i.e., a square
bracket. Square brackets are used to perform indexing in a string to get the value at a
specific index or position. This is also called subscript operator. The index breakdown
for the string "be yourself" assigned to word_phrase string variable is shown below:
With string slicing, you can access a sequence of characters by specifying a range of
index numbers separated by a colon. String slicing returns a sequence of characters
beginning at start and extending up to but not including end. The start and end
indexing values have to be integers. String slicing can be done using either positive or
negative indexing.
The negative index can be used to access individual characters in a string. Negative
indexing starts with −1 index corresponding to the last character in the string and then
the index decreases by one as we move to the left.
1. >>> healthy_drink[-3:-1]
'te'
2. >>> healthy_drink[6:-1]
'te'
You need to specify the lowest negative integer number in the start index position when
using negative index numbers as it occurs earlier in the string ➀. You can also combine
positive and negative indexing numbers ➁.
1. Specifying Steps in Slice Operation: In the slice operation, a third argument
called step which is an optional can be specified along with the start and end index
numbers. This step refers to the number of characters that can be skipped after the start
indexing character in the string. The default value of step is one. In the previous slicing
examples, step is not specified and in its absence, a default value of one is used. For
example,
1. >>> newspaper = "new york times"
2. >>> newspaper[0:12:4]
'ny'
3. >>> newspaper[::4]
In ➁ the slice [0:12:4] takes the character at 0th index which is n and will print every
4th character in the string extending till the 12th character (excluding). You can omit
both start and end index values to consider the entire range of characters in the string by
specifying two colons while considering the step argument which will specify the
number of characters to skip ➂.
2. Joining Strings Using join() Method
Strings can be joined with the join() string. The join() method provides a flexible way to
concatenate strings. The syntax of join() method is,
string_name.join(sequence)
Here sequence can be string or list. If the sequence is a string, then join() function
inserts string_name between each character of the string sequence and returns the
concatenated string. If the sequence is a list, then join() function inserts string_name
between each item of list sequence and returns the concatenated string. It should be
noted that all the items in the list should be of string type.
1. >>> date_of_birth = ["17", "09", "1980"]
2. >>> ":".join(date_of_birth)
'17:09:1980'
3. >>> social_app = ["instagram", "is", "an", "photo", "sharing", "application"]
4. >>> " ".join(social_app)
'instagram is an photo sharing application'
5. >>> numbers = "123"
6. >>> characters = "amy"
7. >>> password = numbers.join(characters)
8. >>> password
'a123m123y'
All the items in the list date_of_birth list variable is of string type ➀. In ➁ the string ":"
is inserted between each list item and the concatenated string is displayed. In social_app
list variable, all the list items are of string type ➂. In ➃, the join() method ensures a
blank space is inserted between each of the list items in social_app and the concatenated
string is displayed. The variables numbers ➄ and characters ➅ are of string type. The
string value of "123" is placed between each character of "amy" string resulting in
'a123m123y'. The string value of "123" is inserted between a and m and again between
m and y and is assigned to password string variable.
String Methods: We can get a list of all the methods associated with string by passing
the str function to dir().
1. >>> dir(str)
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__',
'__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__',
'__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__
mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__',
'__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__',
'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format',
'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower',
'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip',
'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip',
'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
Various methods associated with str are displayed ➀.
Built-in functions of string:Example:
str=”data structure”
s1= “hello365”
s2= “python”
s3 = ‘4567’
s4 = ‘ ‘
s5= ‘comp34%@’
1. Write a program that takes a string with multiple words and then
capitalize the firstletter of each word and forms a new string out of it.
Solution:
length=len(s1)
a=0
end=length
s2="" #empty string
while a<length:
if a==0:
s2=s2+s1[0].upper()
a+=1
elif (s1[a]==' 'and s1[a+1]!=''):
s2=s2+s1[a]
s2=s2+s1[a+1].upper()
a+=2
else:
s2=s2+s1[a]
a+=1
print("Original string : ", s1)
print("Capitalized words string: ", s2)
2. Write a program that reads a string and checks whether it is a
palindrome string ornot.
str=input("Enter a string : ")
n=len(str)
mid=n//2
rev=-1
for i in range(mid):
if str[i]==str[rev]:
i=i+1
rev=rev-1
else:
print("String is not palindrome")
break
print("String is palindrome")