Python - Data Type String Methods

Introduction

String operation can be a sequence operation.

String is a sequence and Python sequence is an data structure.

These operations will work on other sequences in Python as well, including lists and tuples.

In addition to generic sequence operations, strings have operations of their own.

The string find method is the basic substring search operation.

It returns the offset of the passed-in substring, or -1 if it is not present.

The string replace method performs global searches and replacements:

Demo

S = 'test' 
print( S.find('e') )                 # Find the offset of a substring in S 
print( S )
print( S.replace('e', 'XYZ') )       # Replace occurrences of a string in S with another 
print( S )

Result

For these string methods, we are not changing the original strings here, but creating new strings as the results.

Python strings are immutable.

The following code shows other methods you can use with a string:

Demo

line = 'aaa,bbb,ccccc,dd' 
print( line.split(',') )              # Split on a delimiter into a list of substrings 
S = 'test' 
print( S.upper() )                    # Upper- and lowercase conversions 
print( S.isalpha() )                  # Content tests: isalpha, isdigit, etc. 
# from ww w  .  j a  v a  2  s . co m
line = 'aaa,bbb,ccccc,dd\n' 
print( line.rstrip() )                # Remove whitespace characters on the right side 
print( line.rstrip().split(',') )     # Combine two operations

Result

Here, the last command strips before it splits because Python runs from left to right.

Strings support an advanced substitution operation known as formatting.

The formatting is available as both an expression and a string method call:

Demo

print( '%s, eggs, and %s' % ('test', 'TEST!') )          # Formatting expression (all) 
print( '{0}, eggs, and {1}'.format('test', 'TEST!') )    # Formatting method (2.6+, 3.0+) 
print( '{}, eggs, and {}'.format('test', 'TEST!') )      # Numbers optional (2.7+, 3.1+) 
print( '{:,.2f}'.format(2345678.2567) )                   # Separators, decimal digits 
print( '%.2f | %+05d' % (3.14159, -42) )                 # Digits, padding, signs
# from w  w w .  j a  v a 2 s.com

Result

Related Topic