Python Text Sequence Types

PythonProgrammingServer Side Programming

In python the str object, handles the text or string type data. Strings are immutable. The strings are sequence of Unicode characters. We can use single quote, double quotes or triple quotes to define the string literals.

  • ‘This is a string with single quote’
  • “Another Text with double quotes”
  • ‘’’Text using three single quotes’’’ or “””Text using three double quotes”””

We can use triple quotes to assign multiline strings in python.

There is different string related functions. Some of the String methods are as follows −

Sr.No. Operation/Functions & Description
1

s.capitalize()

Convert first character to capital letter

2

s.center(width[, fillchar])

Pad String with specified character. Default is ‘ ’ <space>

3

s.count(sub[, start[, end]])

Count number of occurrences in string

4

s.find(sub[, start[, end]])

Returns the first occurrence of substring in the text

5

s.format(*args, **kwargs)

Format the string to generate nice output

6

s.isalnum()

Check for alphanumeric characters

7

s.isalpha()

Check whether all characters are alphabets

8

s.isdigit()

Check digit characters

9

s.isspace()

Checks whitespaces in the string

10

s.join(iterable)

Concatenate strings

11

s.ljust(width[, fillchar])

Return the left justified string

12

s.rjust(width[, fillchar])

Return the right justified string

13

s.lower()

Convert to lower case letters

14

s.split(sep=None, maxsplit=-1)

Split the string with given separator

15

s.strip([chars])

Cut the characters from string

16

s.swapcase()

Convert lowercase to uppercase and vice versa

17

s.upper()

Convert to uppercase letters

18

s.zfill(width)

Convert the string by adding zeros with it.

Example Code

Live Demo

myStr1 = 'This is a Python String'
myStr2 = "hello world"

print(myStr2)
print(myStr2.capitalize())

print(myStr2.center(len(myStr1)))
print(myStr1)

print(myStr1.find('Py')) #The location of substring Py.
myStr3 = 'abc123'
print(myStr3.isalnum())
print(myStr3.isdigit())

print('AB'.join('XY'))
print(myStr2.rjust(20, '_')) #Right justified string, filled with '_' character
print(myStr1.swapcase())

print('2509'.zfill(10)) #Fill 0s to make 10 character long string

Output

hello world
Hello world
      hello world      
This is a Python String
10
True
False
XABY
_________hello world
tHIS IS A pYTHON sTRING
0000002509
raja
Updated on 30-Jul-2019 22:30:23

Advertisements