Linux

Python Strings

in this section we will examine the internal structure of a Python Strings.
String : A Python string is a sequence of zero or more characters.
The string is an immutable data structure. Although you can access the internal data elements but can not modified.
Sequences fall into one of two categories:mutable or immutable.
Mutable means changeable. Mutable sequence is one that can change. Immutable means unchangeable, means that can not be change. Python strings are immutable sequences, which means that they can't change. So,for example, the string "Satyamev Jayte " will always be the string "Satyamev Jayte " In order to find the lenght of Python string, function len(string) is used, see the example below.

Example 1:

To calculate length of string len()
len()

The Subscript Operator

Sometimes user want to examine one character of string at a given position without analysing them all. The subscript operator makes this possible. The syntax and example of subscript operator is given below:
<given string>[<index>]
The given Python string is that you want to examine, The index is an integer means the position of particular character as shown in example below. In the following examples, the subscript operator is used to access characters in the string "Hello Jarvis".

Example 2:

Python subscript operator
subscript operator
I hope you can understand the subscript operator. The "hello jarvis" is 12 character long means [0:11]. The name[0] respresent the character 'h'. name[12] genrate error "out of range", name[-1] respresents the last character of the Python string and name[-12] represents the first character of the string. See the figure below:
Python String Indexing
Indexing


Slicing for Substrings

The extracted portions of Python strings called substrings. In many situations, you need some portion of string such as first 2 characters of a strings. Python's subscript operator uses a process called slicing. In slicing colon : is used. An integer value will appear on either side of colon. See the example below:

Example 3:

Python Slicing sub-string
slicing
Now we will examine the Python string operations.

Python String Operations

There are several Python string operations, will be discussed one by one. In Python string functions string str will be used.

center()

Syntax
str.center(width[, fillchar])

The method center() makes str centred by taking width parameter into account. Padding is specified by parameter fillchar. Default filler is a space.
str = "Germany won the FIFA CUP"
str1= str.center(30,'a')
str2= str.center(30)
print str1
print str2
Out-put
Python String center()
Python String center()

count()

Syntax
str.count(substr [, start [, end]])
The method str.count(substr [, start [, end]]) returns the number of occurrence of Python string substr in string str. By using parameter start and end you can give slice of str .
str = "Ths is a count example"
sub = "i"
print str.count(sub, 4, len(str))
sub = "a"
print str.count(sub)
Out-put
Python string count()
Python string count()
I hope you can understand the above code, in str.count(sub, 4, len(str)) parameter 4 and len(str) represent the slice of Python string str

endswith()

This method returns True if the string ends with the specified substring, otherwise return False Syntax
str.endswith(suffix[, start[, end]])
The use of start and end to generate slice of Python string str
str ="it is not easy to play another man's game"
sub = "is"
print str.endswith(sub,2,5)
print str.endswith(sub,30)
sub = "game"
print str.endswith(sub)
Out-put
Python string endswith()
endswith()
First result is true, because substring "is" is examined in slice 2 to 5 position of Python string str. Second result is false and third result is true.

find()

Syntax
str.find(str, beg=0 end=len(string))
The find() method used to find out whether a string occur in given string or its substrings.
str ="it is not easy to play another man's game"
print str
print "\n"
str1="man"
str2= "woman"
print str.find(str1)
print str.find(str1,38)
print str.find(str2)
Out-put
Python string find()
find()
If given Python string is found, then the find() method returns its index. If Python string is not found then -1 would be returned.

isalnum()

Syntax
str.isalnum()

The method isalnum() is used to determine whether the Python string consists of alphanumeric characters,false otherwise.
Out-put
Python string isalnum()
isalnum()

isalpha()

Syntax
str.isalpha()

The method isalpha() return true if the Python string contains only alphabetic character(s),false otherwise.
Out-put
Python string isalpha()
isalpha()

isdigit()

Syntax
str.isdigit()

The method isdigit() return true if the Python string contains only digit(s),false otherwise. Example shows rest story
Out-put
Python string isdigit()
isdigit()

islower()

Syntax
str.islower()

The method islower() return true if the Python string contains only lower cased character(s), false otherwise. Example shows rest story
Out-put
Python string islower()
islower()

isspace()

Syntax
str.isspace()

The method isspace() return true if the Python string contains only white space(s). Example shows rest story
Out-put
Python string isspace()
isspace

istitle()

Syntax
str.istitle()

The method istitle() return true if the string is a titlecased. Example shows rest of the story.
Out-put
Python string istitle()
istitle()

isupper()

Syntax
str.isupper()

The method isupper() return true if the string contains only upper cased character(s), false otherwise. . Example shows rest story
Out-put
Python string isupper()
isupper()

ljust()

Syntax
str.ljust(width[, fillchar])

When you provide the string to the method ljust(), it returns the string left justified. Total length of string is defined in first parameter of method width . Padding is done as defined in second parameter fillchar .( default is space)
Out-put
Python string ljust()
ljust()
In above example you can see that if you don't define the fillchar then the method ljust() automatically take space as fillchar.

rjust()

Syntax
str.rjust(width[, fillchar])

When you provide the string to the method rjust(), it returns the string right justified. Total length of string is defined in first parameter of method width . Padding is done as defined in second parameter fillchar .( default is space)
Out-put
Python string rjust()
rjust

capitalize()

This function capitalizes first letter of string.
Python string capitalize()
capitalize()

lower()

Syntax
str.lower()

The method lower() returns a copy of the string in which all case-based characters have been converted to lower case.
Python string lower()
lower()

upper()

Syntax
str.upper()

The method upper() returns a copy of the string in which all case-based characters have been converted to upper case.
Python string upper()
upper()

title()

Syntax
str.title()

The method title() returns a copy of the string in which first character of all words of string are capitalised.
Python string title()
title()

swapcase()

Syntax
str.swapcase()

The method swapcase() returns a copy of the string in which all cased based character swap their case .
Python string swapcase()
swapcase()

join()

Syntax
str.join(seq)

seq = it contains the seqeunce of separated strings.
str = it is the string which is used to replace the separator of seqcence
This method join() returns a string which is the concatenation of given sequence and string as shown in example.
Python string lower()
lower()

lstrip()

Syntax
str.lstrip([chars])

The method lstrip() returns a copy of the string in which specified char(s) have been stripped from left side of string. If char is not specified then space is taken as default.
Python string lstrip()
lstrip()

rstrip()

Syntax
str.rstrip([chars])

The method lstrip() returns a copy of the string in which specified char(s) have been stripped from right side of string. If char is not specified then space is taken as default.
Python string rstrip()
rstrip

strip()

Syntax
str.strip([chars])

The method lstrip() returns a copy of the string in which specified char(s) have been stripped from both side of string. If char is not specified then space is taken as default.
Python string rstrip()
strip

split()

The method splits returns a list of all words in the string, delimiter separates the words. If delimiter is not specified then whitespace is taken as delimiter, paramter num Syntax str.split("delimiter", num)
Python string split()
split()

max()

Syntax
max(str)

The method max() returns the max character from string str according to ASCII value. in first print statement y is max character, because ASCII code of "y" is 121. In second print statement "s" is max character, ASCII code of "s" is 115.
Python string max()
max()

min()

Syntax
min(str)

The method min() returns the min character from string str according to ASCII value.
Python string min()
min()

replace()

Syntax
str.replace(old, new[, max])

The method replace() returns the string in which occurrences of string specified by parameter old have been replaced with string specified by parameter new . The parameter max defined how many occurrences have been replaced. If max is not specified then all occurrences will be replaced.
Python string replace()
replace()

splitlines()

Syntax
str.splitlines( num)
The method splitlines() returns a list with all the lines in string, In num is specified then it would include line break.
num -- This is any number, if present then it would be assumed that line breaks need to be included in the lines.
Python string splitlines()
splitlines()
When you supplied num greater than 1 it include line break.

startswith()

Syntax
str.startswith(str1, beg=0,end=len(string));

The method startswith() return true if a string str starts with the string specified by parameter str1. parameter beg and end are used to slice the string str .
Python string startswith()
startswith()

zfill()

Syntax
str.zfill(width)

This method pads the string on the left with zeros to fill width.
Python string zfill()
zfill()
You have leaned about strings operation in Python, I hope you enjoyed the chapter.




admin