All Courses
Python String

Python String

May 17th, 2019 python

Python String

Strings are represented as collection of characters. It is immutable. We can represent single quotes or double quotes to represent strings.
To use multi-line char’s, we use triple quotes to represent strings.

Example:

str = input(“enter your programming language”)

print(str)

The above example gets input string from user and prints it. Python version 2, we use raw_input method instead of input()
Consider a string,
str = “python”
we can use slicing to extract each char’s.

Example:

str[0]   #p

str[0:2]  #py

Let’s understand the basic methods in brief

1. capitalize()

Converts first char in to capital letter.

Example:

str = “python”
print(str.capitalize())

Output:

Python

2. Center()

It returns a string which is padded with the specified character.

Example

str = “python”

print(str.center(15,’*’))

output:

*****python****

3. count()

Count the occurrences or substring in a string.

Example:

str = ‘python is very easy to learn’

Output:

print(str.count(‘o’))

2

4. lower()

Returns all the char’s into lower case. upper() is the reverse process.

Example:

str = “PYTHON”

print(str.lower())

Output:

python

Similarly, you can try upper().

5. startswith()

Checks the given char is starting in the specified string.

Example:

print(str.startswith(‘p’))

Output:

True

Similarly, you can check endwith() method to find the char ended in the string or not.

6. find()

Returns the index of the given substring position. If the value is not found it returns, -1.

Example:

str = “python”

print(str.find(‘p’))

0

print(str.find(‘z’))

-1

Similarly you can use rfind() to check from right side.

7. format()

formats the given string.

Example:

print(“{0} is {1} to learn program”.format(‘python’,’easy’))

Output:

python is easy to learn program

8. index()

Returns the index position of the given string.

Example:

str = “python”

print(str.index(‘p’))

Output:

0

You can access in for loop,

Example:

for i in str:

print(str.index(i))

Output:

0

1

2

3

4

5

9. strip()

Removes both left side and right side whitespaces.

Example:

str = “    this is easy to learn   “

print(str.strip())

Output:

this is easy to learn.

If you want to remove only left side, lstrip() is used.
rstrip() is used for right side removing whitespaces.

10. title()

It converts all the char’s first starting letter into capital letter.

Example:

str = “hi python”

print(str.title())

Output:

Hi Python

11. isalnum ()

It checks the string contains either alphabets or numbers.

12. isupper()

checks the given string is upper case or not. similarly, you can find islower().

13.Casefold

case fold – Converts all the characters to lower

Example

c = “123Hello”
a = “HellO worLd”
b = a.casefold()
print(b)
print(b.casefold())

Output

hello world
hello world

14. Encode

encode #execute this in command prompt, it depends upon the ide which supports the special character

Example

myencodedstring = “I Ã¥m leărn\\ing PythÅ on”
print(myencodedstring.encode(encoding = ‘ascii’, errors =
‘backslashreplace’))
print(myencodedstring.encode(encoding = ‘ascii’, errors = ‘ignore’))
print(myencodedstring.encode(encoding = ‘ascii’, errors = ‘namereplace’))
print(myencodedstring.encode(encoding = ‘ascii’, errors = ‘strict’))
print(myencodedstring.encode(encoding = ‘ascii’, errors = ‘replace’))
print(myencodedstring.encode(encoding = ‘ascii’, errors =
‘xmlcharrefreplace’))
print(“\n”)
print(myencodedstring.encode(encoding = ‘cp437’, errors =
‘backslashreplace’))
print(myencodedstring.encode(encoding = ‘cp437’, errors = ‘ignore’))
b’I \x86m le\\u0103rning Pyth\\u0160on’
b’I \x86m lerning Python’
b’I \\N{LATIN SMALL LETTER A WITH RING ABOVE}m le\\N{LATIN SMALL LETTER A
WITH BREVE}rning Pyth\\N{LATIN CAPITAL LETTER S WITH CARON}on’
b’I ?m le?rning Pyth?on’
b’I åm leărning PythŠon’

15.Endswith

Example:

infotext = “Welcome to Python”
print(infotext.endswith(“Python”))
print(infotext[0:7])
print(infotext.endswith(“Welcome”,0,7))
print(infotext[2:8])
print(infotext.endswith(“Welcome”,2,8))
infotext1 = “Welcome to Python ”
print(infotext1[0:8])
print(infotext1.startswith(“Welcome”,0,8))
print(infotext1.endswith(“Welcome”,0,8))

Output

True
me to Python
False
Welcome
True
True
Welcome
True
lcome
False
Welcome
True
False

16.Expandtabs

Example

#mytabbedstring = “H e l l o”
mytabbedstring = “H\te\tl\tl\to”
print(mytabbedstring)
print(mytabbedstring.expandtabs(0))
print(mytabbedstring.expandtabs(2))
print(mytabbedstring.expandtabs(4))
print(mytabbedstring.expandtabs(tabsize = 5))
print(mytabbedstring.expandtabs(6))
print(mytabbedstring.expandtabs(8))
print(“\n”)

Output

welcome to my world1
welcome tomy world2
welcome to my world3
H e l l o
Hello
H e l l o
H e l l o
H e l l o
H e l l o
H e l l o

17.Split

Example

Fruits = “apple,orange, grapes, guava, pineapple”
#Split(“characterseparator”,max) max -maximum no of times to split
AllFruits = Fruits.split(“,”)
print(AllFruits)
ThreeFruits = Fruits.split(“,”,2)
print(ThreeFruits)
[‘apple’, ‘orange’, ‘ grapes’, ‘ guava’, ‘ pineapple’] [‘apple’, ‘orange’, ‘ grapes, guava, pineapple’]

18.Isalpha,Isdecimal

Alpha, Alphanumeric and Decimal Checking

Example

myalpha =”abcd” #contains characters [a-zA-Z] myalphanumeric = “abcdef123” #contains characters [a-zA-Z0-9] mynotalphanumeric= “&abcdef123″ # Not fitting all three cases (Contain a
symbol)
mydecimal =”123” #contains characters [0-9] print(“myalpa string is alpha – {}”.format(myalpha.isalpha()))
print(“myalphanumeric string is alpha –
{}”.format(myalphanumeric.isalpha()))
print(“mynotalphanumeric string is alpha –
{}”.format(mynotalphanumeric.isalpha()))
print(“mydecimal string is alpha – {}”.format(mydecimal.isalpha()))
print(“\n”)
print(“myalpa string is alphanumeric – {}”.format(myalpha.isalnum()))
print(“myalphanumeric string is alphanumeric –
{}”.format(myalphanumeric.isalnum()))
print(“mynotalphanumeric string is alphanumeric –
{}”.format(mynotalphanumeric.isalnum()))
print(“mydecimal string is alphanumeric – {}”.format(mydecimal.isalnum()))
print(“\n”)
print(“myalpa string is decimal – {}”.format(myalpha.isdecimal()))
print(“myalphanumeric string is decimal –
{}”.format(myalphanumeric.isdecimal()))
print(“mynotalphanumeric string is decimal –
{}”.format(mynotalphanumeric.isdecimal()))
print(“mydecimal string is decimal – {}”.format(mydecimal.isdecimal()))

Output

myalpa string is alpha – True
myalphanumeric string is alpha – False
mynotalphanumeric string is alpha – False
mydecimal string is alpha – False
myalpa string is alphanumeric – True
myalphanumeric string is alphanumeric – True
mynotalphanumeric string is alphanumeric – False
mydecimal string is alphanumeric – True
myalpa string is decimal – False
myalphanumeric string is decimal – False
mynotalphanumeric string is decimal – False
mydecimal string is decimal – True

19.Substring

Example

#: stands for sequence
#[] stands for the position holders
#value before the : is the start sequence, after the colon is the end
sequence
# start: end: step
TestString = “Hello Python”
print(TestString[0:5])
print(TestString[:5])
print(TestString[6:12])
print(TestString[5:])
print(TestString[-5:-1])
#print(TestString[::-1])
print(TestString[:-1])
print(TestString[-3:-5])
print(TestString[:])
#print(TestString[:-1:])
#print(TestString[:2:1])
#Reverse a string
print(TestString[::1])
print(TestString[::2])
print(TestString[::3])
print(TestString[::-1])
print(TestString[::-2])

Output

Hello
Hello
Python
Python
ytho
Hello Pytho
Hello Python
Hello Python
HloPto
HlPh
nohtyP olleH
nhy le

Social Share:

0 responses on "Python String"

Leave a Message

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