Python Strings with Program Examples

Spread the love

Sting is a set of characters. you can define with single, double and tipple quotes in python. We have inbuilt string functions to make easy process.

Python String Methods

a= "Hello python"

print(a)

Output: 

Hello python

 

#code

print(a[0])

Output:

H

slicing of string or subset of string

print("\nSlicing of string")
print(a[0:5])

print(a[5:])

print(a[:-4])

Output:

Slicing of string
Hello
python
Hello py

length of string

print("\nlength of string")

print(len(a))

Output:

length of string
12

Capitalize all characters

print(a.upper())

Output:

HELLO PYTHON

Convert all characters to small characters

print(a.lower())

Output:

hello python

#Return a title cased version of the string

print(a.title())

Output:

Hello Python

Return true if there are only whitespace characters in the string

print(a.isspace())

Output: 

False

#Return the number of non-overlapping occurrences of substring

print(a.count('H'))

Output: 1

#Return an encoded version of the string as a bytes object

print(a.encode(encoding="utf-32", errors="strict"))

Output:

b'\xff\xfe\x00\x00H\x00\x00\x00e\x00\x00\x00l\x00\x00\x00l\x00\x00\x00o\x00\x00\x00 \x00\x00\x00p\x00\x00\x00y\x00\x00\x00t\x00\x00\x00h\x00\x00\x00o\x00\x00\x00n\x00\x00\x00'

#Return True if the string ends with the specified suffix, otherwise return False

print(a.endswith('.'))

Output:

False

#Return true if all characters in the string are alphabetical

print(a.isalpha())

Output:

False

#Return a list of the words in the string, using sep as the delimiter string.

print(a.split(' '))

Output:

['Hello', 'python']

#Return True if string starts with the prefix, otherwise return False.

print(a.startswith('H'))

Output: 

True

#Return True if string ends with the prefix, otherwise return False.

print(a.endswith('.'))

Output: 

False

#Return the lowest index in the string where substring sub is found within the slice

it return ‘0’ if he string found and ‘-1’ not found

print(a.find('Hello'))

Output:

0

# the old sub string to new

print(a.replace('Hello','New'))

Output:

New python

#returns index value

print(a.index('python'))

Output:

6

# adding a sub string to main string

print(a.join('Hi '))

Output:

HHello pythoniHello python

Ref: https://docs.python.org/2/library/string.html

admin

admin

Leave a Reply

Your email address will not be published. Required fields are marked *