Python String Data Type Tutorial With Practical Example

Hello Guyz,

Todays, Post Is Completely Dedicated To Python Programmers Newbies. Today, In This Post I am going to show you various types of String Datatypes Function And Operations For String Manipulations. If You are new In python Programming Then, This Post is Really Very Useful For You.

So, Let's Quickly Start Our Practical Example Tutorial

Python String Data Type Manipulation Function Examples

Input : [1]

```#!/usr/bin/python
#
# here, I am using
#
#     Ubuntu 18.04
#     Python 2.7
#     Jupyter Notebook
#
#   For More Detail Informations About Functions
#        Check Official Documentation :
#                 https://docs.python.org/2/library/stdtypes.html#string-methods
#
```

Output : [1]

```
```

Input : [2]

```# Python Supported DataTypes

a = "Cat"      # String

b = 12    # Integers

c = 12.5  # Float

d = (a, b, c) # Tuple

e = [a, b, c, d] # List

f = {            # Dictionery
"String":a,
"Integer":b,
"Float" : c,
"Tuple": d,
"List": e
}

print "String     : ", a

print "Integers   : ", b

print "Float      : ", c

print "List       : ", d

print "Dictionery : ", e
```

Output : [2]

```String     :  Cat
Integers   :  12
Float      :  12.5
List       :  ('Cat', 12, 12.5)
Dictionery :  ['Cat', 12, 12.5, ('Cat', 12, 12.5)]
```

Input : [3]

```# String Supported Operations

print "-"*80
print "       Input       |              Operation             |      Output"
print "-"*80

# str.capitalize()
# Return a copy of the string with its first
# character capitalized and the rest lowercased.

print " A = "+a+ " | "+" Capitalize All Words              : ",a.capitalize()

# str.center(width[, fillchar])
# Return centered in a string of length width.
# Padding is done using the specified fillchar (default is a space).

print " A = "+a+ " | "+" Keep word in center               : ",a.center(5)

# str.count(sub[, start[, end]])
# Return the number of non-overlapping occurrences
# of substring sub in the range [start, end]. Optional arguments
# start and end are interpreted as in slice notation.

print " A = "+a+ " | "+" Count Number of Character         : ",a.count("S")

# str.decode([encoding[, errors]])
# Decodes the string using the codec registered for encoding.
# encoding defaults to the default string encoding. errors may be given to
# set a different error handling scheme. The default is 'strict',
# meaning that encoding errors raise UnicodeError. Other possible
# values are 'ignore', 'replace' and any other name registered via codecs.register_error(),
#

# str.encode([encoding[, errors]])
# Return an encoded version of the string.
# Default encoding is the current default string encoding.
# errors may be given to set a different error handling scheme.
# The default for errors is 'strict', meaning that encoding errors
# raise a UnicodeError. Other possible values are 'ignore', 'replace',
# 'xmlcharrefreplace', 'backslashreplace' and any other name registered
# via codecs.register_error(), see section Codec Base Classes.
# For a list of possible encodings, see section Standard Encodings.

print " A = "+a+ " | "+" Encode String                     : ",a.encode('hex')

# str.endswith(suffix[, start[, end]])
# Return True if the string ends with the specified suffix,
# otherwise return False. suffix can also be a tuple of suffixes to look for.
# With optional start, test beginning at that position. With optional end,
# stop comparing at that position.

print " A = "+a+ " | "+" Check String End                  : ",a.endswith('a')

# str.expandtabs([tabsize])
# Return a copy of the string where all tab characters are
# replaced by one or more spaces, depending on the current column
# and the given tab size. Tab positions occur every tabsize characters
# (default is 8, giving tab positions at columns 0, 8, 16 and so on).
# To expand the string, the current column is set to zero and
# the string is examined character by character. If the character
# is a tab (\t), one or more space characters are inserted in the result
# until the current column is equal to the next tab position.
# (The tab character itself is not copied.) If the character is a newline (\n)
# or return (\r), it is copied and the current column is reset to zero.
# Any other character is copied unchanged and the current column is incremented
# by one regardless of how the character is represented when printed.

print " A = "+a+ " | "+" Expand All Tabs                   : ",a.expandtabs(5)

# str.find(sub[, start[, end]])
# Return the lowest index in the string where substring sub is
# found within the slice s[start:end]. Optional arguments start
# and end are interpreted as in slice notation. Return -1 if sub is not found.

print " A = "+a+ " | "+" Find Character Index Num.         : ",a.find("a")

# str.format(*args, **kwargs)
# Perform a string formatting operation. The string on which this
# method is called can contain literal text or replacement fields
# delimited by braces {}. Each replacement field contains either
# the numeric index of a positional argument, or the name of a
# keyword argument. Returns a copy of the string where each replacement
# field is replaced with the string value of the corresponding argument.

print " A = "+a+ " | "+" Return Formated String            : ",a.format()
```

Output : [3]

```--------------------------------------------------------------------------------
Input       |              Operation             |      Output
--------------------------------------------------------------------------------
A = Cat |  Capitalize All Words              :  Cat
A = Cat |  Keep word in center               :   Cat
A = Cat |  Count Number of Character         :  0
A = Cat |  Encode String                     :  436174
A = Cat |  Check String End                  :  False
A = Cat |  Expand All Tabs                   :  Cat
A = Cat |  Find Character Index Num.         :  1
A = Cat |  Return Formated String            :  Cat
```

Input : [4]

```print "\n"

print "+" * 50

print " " * 10 +" Various Check Conditions "

print "-" * 50

print " A = "+a+ " | "+" Is String Characters Alphanumeric : ",a.isalnum()

# str.isalpha()
# Return true if all characters in the string are alphabetic and
# there is at least one character, false otherwise.

print " A = "+a+ " | "+" Is String Characters Alphabetic   : ",a.isalpha()

# str.isdigit()
# Return true if all characters in the string are digits
# and there is at least one character, false otherwise.

print " A = "+a+ " | "+" Is String Characters Digit        : ",a.isdigit()

# str.islower()
# Return true if all cased characters [4] in the string are
# lowercase and there is at least one cased character, false otherwise.

print " A = "+a+ " | "+" Is String Characters Lower Case   : ",a.islower()

# str.isspace()
# Return true if there are only whitespace characters in the
# string and there is at least one character, false otherwise.

print " A = "+a+ " | "+" Is String Characters Has Space    : ",a.isspace()

# str.istitle()
# Return true if the string is a titlecased string and
# there is at least one character, for example uppercase characters may only
# follow uncased characters and lowercase characters only cased ones. Return false otherwise.

print " A = "+a+ " | "+" Is String Characters Has Title    : ",a.istitle()

# str.isupper()
# Return true if all cased characters [4] in the string are uppercase
# and there is at least one cased character, false otherwise.

print " A = "+a+ " | "+" Is String Characters Upper Case   : ",a.isupper()
```

Output : [4]

```++++++++++++++++++++++++++++++++++++++++++++++++++
Various Check Conditions
--------------------------------------------------
A = Cat |  Is String Characters Alphanumeric :  True
A = Cat |  Is String Characters Alphabetic   :  True
A = Cat |  Is String Characters Digit        :  False
A = Cat |  Is String Characters Lower Case   :  False
A = Cat |  Is String Characters Has Space    :  False
A = Cat |  Is String Characters Has Title    :  True
A = Cat |  Is String Characters Upper Case   :  False
```

Input : [5]

```a = "Bitforestinfo"

# String Supported Operations

print "-"*80

print "       Input       |              Operation             |      Output"

print "-"*80

print " A = "+a+ " | "+"Join Two String                  :",'-'.join(a)

print " A = "+a+ " | "+"Left Side Justify                :",a.ljust(10)

print " A = "+a+ " | "+"Lower Case                       :",a.lower()

print " A = "+a+ " | "+"Left Side Strip                  :",a.lstrip("o")

print " A = "+a+ " | "+"String Partition                 :",a.partition('f')

print " A = "+a+ " | "+"String Replace Function          :",a.replace('res', "RES")
```

Output : [5]

```--------------------------------------------------------------------------------
Input       |              Operation             |      Output
--------------------------------------------------------------------------------
A = Bitforestinfo | Join Two String                  : B-i-t-f-o-r-e-s-t-i-n-f-o
A = Bitforestinfo | Left Side Justify                : Bitforestinfo
A = Bitforestinfo | Lower Case                       : bitforestinfo
A = Bitforestinfo | Left Side Strip                  : Bitforestinfo
A = Bitforestinfo | String Partition                 : ('Bit', 'f', 'orestinfo')
A = Bitforestinfo | String Replace Function          : BitfoREStinfo
```

Input : [6]

```# String Supported Operations
print "-"*80

print "       Input       |              Operation             |      Output"

print "-"*80

print " A = "+a+ " | "+"Find Character (From Right Side) :",a.rfind('o')

print " A = "+a+ " | "+"Find Index  (From Right Side)    :",a.rindex("i")

print " A = "+a+ " | "+"Justify String  (From Right Side):",a.rjust(10)

print " A = "+a+ " | "+"Partition  (From Right Side)     :",a.rpartition("f")

print " A = "+a+ " | "+"Split String  (From Right Side)  :", a.rsplit("i")

print " A = "+a+ " | "+"Strip String  (From Right Side)  :",a.rstrip("o")
```

Output : [6]

```--------------------------------------------------------------------------------
Input       |              Operation             |      Output
--------------------------------------------------------------------------------
A = Bitforestinfo | Find Character (From Right Side) : 12
A = Bitforestinfo | Find Index  (From Right Side)    : 9
A = Bitforestinfo | Justify String  (From Right Side): Bitforestinfo
A = Bitforestinfo | Partition  (From Right Side)     : ('Bitforestin', 'f', 'o')
A = Bitforestinfo | Split String  (From Right Side)  : ['B', 'tforest', 'nfo']
A = Bitforestinfo | Strip String  (From Right Side)  : Bitforestinf
```

Input : [7]

```# String Supported Operations
print "-"*80

print "       Input       |              Operation             |      Output"

print "-"*80

print " A = "+a+ " | "+"Split String                     :",a.split("i")

print " A = "+a+ " | "+"Split Lines                      :",a.splitlines(0)

print " A = "+a+ " | "+"Check String Starting Characters :",a.startswith("Bit")

print " A = "+a+ " | "+"Strip String Character           :",a.strip("o")

print " A = "+a+ " | "+"Upper Case                       :",a.upper()
```

Output : [7]

```--------------------------------------------------------------------------------
Input       |              Operation             |      Output
--------------------------------------------------------------------------------
A = Bitforestinfo | Split String                     : ['B', 'tforest', 'nfo']
A = Bitforestinfo | Split Lines                      : ['Bitforestinfo']
A = Bitforestinfo | Check String Starting Characters : True
A = Bitforestinfo | Strip String Character           : Bitforestinf
A = Bitforestinfo | Upper Case                       : BITFORESTINFO```

Thanks For Visiting.