0% found this document useful (0 votes)
10 views32 pages

Python String Basics and Methods

The document provides a comprehensive overview of Python strings, including how to create, access, and update them, as well as various string methods and operators. It covers string formatting, built-in methods like capitalize(), count(), and find(), and explains the use of special operators for string manipulation. Additionally, it details methods for checking string properties and performing transformations.

Uploaded by

Mohith Reddy
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)
10 views32 pages

Python String Basics and Methods

The document provides a comprehensive overview of Python strings, including how to create, access, and update them, as well as various string methods and operators. It covers string formatting, built-in methods like capitalize(), count(), and find(), and explains the use of special operators for string manipulation. Additionally, it details methods for checking string properties and performing transformations.

Uploaded by

Mohith Reddy
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

Python Strings

• Python treats single quotes the same as double quotes.


• Creating strings is as simple as assigning a value to a variable.

For example:

var1 = 'Hello World!'


var2 = "Python Programming"
Accessing Values in Strings

• Python does not support a character type; these are treated as strings
of length one, thus also considered a substring.
• To access substrings, use the square brackets for slicing along with
the index or indices to obtain your substring.

For example:

#!/usr/bin/python

var1 = 'Hello World!'


var2 = "Python Programming"
print "var1[0]: ", var1[0]
print "var2[1:5]: ", var2[1:5]

Output:

var1[0]: H
var2[1:5]: ytho
Updating Strings

• You can "update" an existing string by (re)assigning a variable to


another string.
• The new value can be related to its previous value or to a completely
different string altogether.
For example:

#!/usr/bin/python

var1 = 'Hello World!'


print "Updated String :- ", var1[:6] + 'Python'

Output:

Updated String :- Hello Python


String Special Operators

Assume string variable a holds 'Hello' and variable b holds 'Python'

Operator Description Example

Concatenation - Adds values


+ a + b will give HelloPython
on either side of the operator

Repetition - Creates new


* strings, concatenating multiple a*2 will give -HelloHello
copies of the same string

Slice - Gives the character


[] a[1] will give e
from the given index

Range Slice - Gives the


[:] characters from the given a[1:4] will give ell
range

Membership - Returns true if a


in character exists in the given H in a will give 1
string
Membership - Returns true if a
not in character does not exist in the M not in a will give 1
given string

Raw String - Suppresses


actual meaning of Escape
characters. The syntax for raw
strings is exactly the same as
for normal strings with the
exception of the raw string print r'\n' prints \n and print
r/R
operator, the letter "r," which R'\n'prints \n
precedes the quotation marks.
The "r" can be lowercase (r) or
uppercase (R) and must be
placed immediately preceding
the first quote mark.

Format - Performs String


% See at next section
formatting

String Formatting Operator

• One of Python's coolest features is the string format operator %.


• This operator is unique to strings and makes up for the pack of
having functions from C's printf() family.

Ex:

#!/usr/bin/python

print "My name is %s and weight is %d kg!" % ('Zara', 21)

Output:
My name is Zara and weight is 21 kg!

• Here is the list of complete set of symbols which can be used along
with %

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

%G the shorter of %f and %E

Built-in String Methods


Python String capitalize() Method
• It returns a copy of the string with only its first character capitalized.

Syntax
[Link]()
Example
#!/usr/bin/python

str = "this is string example....wow!!!";


print "[Link]() : ", [Link]()
Output:
[Link]() : This is string example....wow!!!

Python String center() Method

• The method center() returns centered in a string of length width.


• Padding is done using the specified fillchar.
• Default filler is a space.

Syntax
[Link](width[, fillchar])
Example
#!/usr/bin/python

str = "this is string example....wow!!!";

print "[Link](40, 'a') : ", [Link](40, 'a')


Output:
[Link](40, 'a') : aaaathis is string example....wow!!!aaaa
Python String count() Method

• The method count() returns the number of occurrences of substring


sub in the range [start, end].
• Optional arguments start and end are interpreted as in slice notation.

Syntax
[Link](sub, start= 0,end=len(string))
Parameters

• sub -- This is the substring to be searched.


• start -- Search starts from this index. First character starts from 0
index. By default search starts from 0 index.
• end -- Search ends from this index. First character starts from 0
index. By default search ends at the last index.

Return Value

Centered in a string of length width.

Example
#!/usr/bin/python

str = "this is string example....wow!!!";


sub = "i";
print "[Link](sub, 4, 40) : ", [Link](sub, 4, 40)
sub = "wow";
print "[Link](sub) : ", [Link](sub)
Result
[Link](sub, 4, 40) : 2
[Link](sub) : 1

Python String endswith() Method


• It returns True if the string ends with the specified suffix, otherwise
return False optionally restricting the matching with the given
indices start and end.

Syntax
[Link](suffix[, start[, end]])
Example
#!/usr/bin/python

str = "this is string example....wow!!!";


suffix = "wow!!!";
print [Link](suffix)

suffix = "is";
print [Link](suffix, 2, 4)
Result
True
True

Python String find() Method

• It determines if string str occurs in string, or in a substring of string


if starting index beg and ending index end are given.

Syntax
[Link](str, beg=0, end=len(string))
Parameters

• str -- This specifies the string to be searched.


• beg -- This is the starting index, by default its 0.
• end -- This is the ending index, by default its equal to the length of
the string.
Example
#!/usr/bin/python

str1 = "this is string example....wow!!!";


str2 = "exam";
print [Link](str2)
print [Link](str2, 10)
print [Link](str2, 40)
Result
15
15
-1

Python String index() Method

• It determines if string str occurs in string or in a substring of string


if starting index beg and ending index end are given.
• This method is same as find(), but raises an exception if sub is not
found.

Syntax
[Link](str, beg=0 end=len(string))
Parameters

• str -- This specifies the string to be searched.


• beg -- This is the starting index, by default its 0.
• end -- This is the ending index, by default its equal to the length of
the string.

Example
#!/usr/bin/python

str1 = "this is string example....wow!!!";


str2 = "exam";
print [Link](str2)
print [Link](str2, 10)
print [Link](str2, 40)
Output:
15
15
Traceback (most recent call last):
File "[Link]", line 8, in
print [Link](str2, 40);
ValueError: substring not found

shell returned 1

Python String isalnum() Method

• The method isalnum() checks whether the string consists of


alphanumeric characters.

Syntax
[Link]()
Example
#!/usr/bin/python

str = "this2009"; # No space in this string


print [Link]()

str = "this is string example....wow!!!";


print [Link]()

Output:

True
False

Python String isalpha() Method


• The method isalpha() checks whether the string consists of
alphabetic characters only.

Syntax
[Link]()
Example
#!/usr/bin/python

str = "this"; # No space & digit in this string


print [Link]()

str = "this is string example....wow!!!";


print [Link]()

Output:

True
False

Python String isdigit() Method

• The method isdigit() checks whether the string consists of digits


only.

Syntax
[Link]()
Example
#!/usr/bin/python

str = "123456"; # Only digit in this string


print [Link]()

str = "this is string example....wow!!!";


print [Link]()
Output:

True
False

Python String islower() Method

• The method islower() checks whether all the case-based characters


(letters) of the string are lowercase.

Syntax
[Link]()
Example
#!/usr/bin/python

str = "THIS is string example....wow!!!";


print [Link]()
str = "this is string example....wow!!!";
print [Link]()

Output:

False
True

Python String isnumeric() Method

• The method isnumeric() checks whether the string consists of only


numeric characters.
• This method is present only on unicode objects.

Note: To define a string as Unicode, one simply prefixes a 'u' to the


opening quotation mark of the assignment. Below is the example.

Syntax
[Link]()
Example

The following example shows the usage of isnumeric() method.

#!/usr/bin/python

str = u"this2009";
print [Link]()
str = u"23443434";
print [Link]()

Output:

False
True

Python String isspace() Method

• The method isspace() checks whether the string consists of


whitespace..

Syntax
[Link]()
Example
#!/usr/bin/python

str = " ";


print [Link]()

str = "This is string example....wow!!!";


print [Link]()

Output:

True
False
Python String istitle() Method

• The method istitle() checks whether all the case-based characters in


the string following non-casebased letters are uppercase and all
other case-based characters are lowercase.

Syntax
[Link]()
Example
#!/usr/bin/python

str = "This Is String Example...Wow!!!";


print [Link]()
str = "This is string example....wow!!!";
print [Link]()

Output:

True
False

Python String isupper() Method

• The method isupper() checks whether all the case-based characters


(letters) of the string are uppercase.

Syntax
[Link]()
Example
#!/usr/bin/python

str = "THIS IS STRING EXAMPLE....WOW!!!";


print [Link]()
str = "THIS is string example....wow!!!";
print [Link]()
Output:

True
False

Python String join() Method

• The method join() returns a string in which the string elements of


sequence have been joined by str separator.

Syntax
[Link](sequence)
Example
#!/usr/bin/python

s = "-";
seq = ("a", "b", "c"); # This is sequence of strings.
print [Link]( seq )

Output:

a-b-c

Python String len() Method

• The method len() returns the length of the string.

Syntax
len( str )
Example
#!/usr/bin/python

str = "this is string example....wow!!!";


print "Length of the string: ", len(str)
Output:

Length of the string: 32

Python String ljust() Method

• The method ljust() returns the string left justified in a string of


length width.
• Padding is done using the specified fillchar (default is a space).
• The original string is returned if width is less than len(s).

Syntax
[Link](width[, fillchar])
Example
#!/usr/bin/python

str = "this is string example....wow!!!";


print [Link](50, '0')

Output:

this is string example....wow!!!000000000000000000

Python String lower() Method

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

Syntax
[Link]()
Example
#!/usr/bin/python

str = "THIS IS STRING EXAMPLE....WOW!!!";


print [Link]()

Output:

this is string example....wow!!!

Python String lstrip() Method

• The method lstrip() returns a copy of the string in which all chars
have been stripped from the beginning of the string (default
whitespace characters).

Syntax
[Link]([chars])
Example
#!/usr/bin/python

str = " this is string example....wow!!! ";


print [Link]()
str = "88888888this is string example....wow!!!8888888";
print [Link]('8')

Output:

this is string example....wow!!!


this is string example....wow!!!8888888

Python String maketrans() Method

Description

• The method maketrans() returns a translation table that maps each


character in the intabstring into the character at the same position in
the outtab string.
• Then this table is passed to the translate() function.

Note: Both intab and outtab must have the same length.

Syntax

Following is the syntax for maketrans() method −

[Link](intab, outtab)
Parameters

• intab -- This is the string having actual characters.


• outtab -- This is the string having corresponding mapping character.

Return Value

• This method returns a translate table to be used translate() function.

Example
#!/usr/bin/python

from string import maketrans # Required to call maketrans function.

intab = "aeiou"
outtab = "12345"
trantab = maketrans(intab, outtab)

str = "this is string example....wow!!!"


print [Link](trantab)

Output:

th3s 3s str3ng 2x1mpl2....w4w!!!

Python String max() Method


Description

• The method max() returns the max alphabetical character from the
string str.

Syntax
max(str)
Parameters

• str -- This is the string from which max alphabetical character needs
to be returned.

Return Value

This method returns the max alphabetical character from the string str.

Example

The following example shows the usage of max() method.

#!/usr/bin/python

str = "this is really a string example....wow!!!";


print "Max character: " + max(str)

str = "this is a string example....wow!!!";


print "Max character: " + max(str)

Output:

Max character: y
Max character: x

Python String min() Method


Description

• The method min() returns the min alphabetical character from the
string str.

Syntax
min(str)
Parameters

• str -- This is the string from which min alphabetical character needs
to be returned.

Return Value

This method returns the min alphabetical character from the string str.

Example
#!/usr/bin/python

str = "this-is-real-string-example....wow!!!";
print "Min character: " + min(str)

str = "this-is-a-string-example....wow!!!";
print "Min character: " + min(str)

Output:

Min character: !
Min character: !

Python String replace() Method


Description

• The method replace() returns a copy of the string in which the


occurrences of old have been replaced with new, optionally
restricting the number of replacements to max.

Syntax
[Link](old, new[, max])
Parameters

• old -- This is old substring to be replaced.


• new -- This is new substring, which would replace old substring.
• max -- If this optional argument max is given, only the first count
occurrences are replaced.

Return Value

• This method returns a copy of the string with all occurrences of


substring old replaced by new.
• If the optional argument max is given, only the first count
occurrences are replaced.

Example
#!/usr/bin/python

str = "this is string example....wow!!! this is really string"


print [Link]("is", "was")
print [Link]("is", "was", 3)

Output:

thwas was string example....wow!!! thwas was really string


thwas was string example....wow!!! thwas is really string

Python String rfind() Method


Description

• The method rfind() returns the last index where the substring str is
found, or -1 if no such index exists, optionally restricting the search
to string[beg:end].

Syntax
[Link](str, beg=0 end=len(string))
Parameters

• str -- This specifies the string to be searched.


• beg -- This is the starting index, by default its 0.
• end -- This is the ending index, by default its equal to the length of
the string.

Return Value

This method returns last index if found and -1 otherwise.

Example
#!/usr/bin/python

str1 = "this is really a string example....wow!!!";


str2 = "is";

print [Link](str2)

print [Link](str2, 0, 10)


print [Link](str2, 10, 0)

print [Link](str2)
print [Link](str2, 0, 10)
print [Link](str2, 10, 0)

Output:
5
5
-1
2
2
-1

Python String rindex() Method

Description

• The method rindex() returns the last index where the substring str
is found, or raises an exception if no such index exists, optionally
restricting the search to string[beg:end].

Syntax

Following is the syntax for rindex() method −

[Link](str, beg=0 end=len(string))


Parameters

• str -- This specifies the string to be searched.


• beg -- This is the starting index, by default its 0
• len -- This is ending index, by default its equal to the length of the
string.

Return Value

This method returns last index if found otherwise raises an exception if


str is not found.

Example
#!/usr/bin/python

str1 = "this is string example....wow!!!";


str2 = "is";

print [Link](str2)
print [Link](str2)

Output:

5
2

Python String rjust() Method

Description

• The method rjust() returns the string right justified in a string of


length width. Padding is done using the specified fillchar (default is
a space).
• The original string is returned if width is less than len(s).

Syntax
[Link](width[, fillchar])
Parameters

• width -- This is the string length in total after padding.


• fillchar -- This is the filler character, default is a space.

Return Value

• This method returns the string right justified in a string of length


width.
• Padding is done using the specified fillchar (default is a space). The
original string is returned if width is less than len(s).

Example

The following example shows the usage of rjust() method.


#!/usr/bin/python

str = "this is string example....wow!!!";

print [Link](50, '0')

Output:

000000000000000000this is string example....wow!!!

Python String rstrip() Method

Description

• The method rstrip() returns a copy of the string in which all chars
have been stripped from the end of the string (default whitespace
characters).

Syntax
[Link]([chars])
Parameters

• chars -- You can supply what chars have to be trimmed.

Return Value

This method returns a copy of the string in which all chars have been
stripped from the end of the string (default whitespace characters).

Example
#!/usr/bin/python

str = " this is string example....wow!!! ";


print [Link]()
str = "88888888this is string example....wow!!!8888888";
print [Link]('8')
Output:

this is string example....wow!!!


88888888this is string example....wow!!!

Python String startswith() Method

Description

• The method startswith() checks whether string starts with str,


optionally restricting the matching with the given indices start and
end.

Syntax
[Link](str, beg=0,end=len(string));
Parameters

• str -- This is the string to be checked.


• beg -- This is the optional parameter to set start index of the
matching boundary.
• end -- This is the optional parameter to end start index of the
matching boundary.

Return Value

This method returns true if found matching string otherwise false.

Example
#!/usr/bin/python

str = "this is string example....wow!!!";


print [Link]( 'this' )
print [Link]( 'is', 2, 4 )
print [Link]( 'this', 2, 4 )

Output:
True
True
False

Python String strip() Method

Description

• The method strip() returns a copy of the string in which all chars
have been stripped from the beginning and the end of the string
(default whitespace characters).

Syntax
[Link]([chars]);
Parameters

• chars -- The characters to be removed from beginning or end of the


string.

Return Value

This method returns a copy of the string in which all chars have been
stripped from the beginning and the end of the string.

Example
#!/usr/bin/python

str = "0000000this is string example....wow!!!0000000";


print [Link]( '0' )

Output:

this is string example....wow!!!


Python String swapcase() Method

Description

• The method swapcase() returns a copy of the string in which all the
case-based characters have had their case swapped.

Syntax
[Link]();
Parameters

• NA

Return Value

This method returns a copy of the string in which all the case-based
characters have had their case swapped.

Example
#!/usr/bin/python

str = "this is string example....wow!!!";


print [Link]()

str = "THIS IS STRING EXAMPLE....WOW!!!";


print [Link]()

Output:

THIS IS STRING EXAMPLE....WOW!!!


this is string example....wow!!!

Python String title() Method


Description

• The method title() returns a copy of the string in which first


characters of all the words are capitalized.

Syntax
[Link]();
Return Value

This method returns a copy of the string in which first characters of all the
words are capitalized.

Example
#!/usr/bin/python

str = "this is string example....wow!!!";


print [Link]()

Output:

This Is String Example....Wow!!!

Python String translate() Method

Description

• The method translate() returns a copy of the string in which all


characters have been translated using table (constructed with the
maketrans() function in the string module), optionally deleting all
characters found in the string deletechars.

Syntax
[Link](table[, deletechars]);
Parameters

• table -- You can use the maketrans() helper function in the string
module to create a translation table.
• deletechars -- The list of characters to be removed from the source
string.

Return Value

This method returns a translated copy of the string.

Example
#!/usr/bin/python

from string import maketrans # Required to call maketrans function.

intab = "aeiou"
outtab = "12345"
trantab = maketrans(intab, outtab)

str = "this is string example....wow!!!";


print [Link](trantab)

Output:

th3s 3s str3ng 2x1mpl2....w4w!!!

Following is the example to delete 'x' and 'm' characters from the string −

#!/usr/bin/python

from string import maketrans # Required to call maketrans function.

intab = "aeiou"
outtab = "12345"
trantab = maketrans(intab, outtab)
str = "this is string example....wow!!!";
print [Link](trantab, 'xm')

Output:

th3s 3s str3ng 21pl2....w4w!!!

Python String upper() Method

Description

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

Syntax
[Link]()
Return Value

This method returns a copy of the string in which all case-based characters
have been uppercased.

Example
#!/usr/bin/python

str = "this is string example....wow!!!";

print "[Link]() : ", [Link]()

Output:

[Link]() : THIS IS STRING EXAMPLE....WOW!!!

Python String zfill() Method


Description

• The method zfill() pads string on the left with zeros to fill width.

Syntax
[Link](width)
Parameters

• width -- This is final width of the string. This is the width which we
would get after filling zeros.

Return Value

This method returns padded string.

Example
#!/usr/bin/python

str = "this is string example....wow!!!";

print [Link](40)
print [Link](50)

Output:

00000000this is string example....wow!!!


000000000000000000this is string example....wow!!!

Python String isdecimal() Method


Description

• The method isdecimal() checks whether the string consists of only


decimal characters. This method are present only on unicode
objects.

Note: To define a string as Unicode, one simply prefixes a 'u' to the


opening quotation mark of the assignment. Below is the example.

Syntax

Following is the syntax for isdecimal() method −

[Link]()
Return Value

This method returns true if all characters in the string are decimal, false
otherwise.

Example
#!/usr/bin/python

str = u"this2009";
print [Link]();

str = u"23443434";
print [Link]();

Output:

False
True

You might also like