Showing posts with label string functions in Python. Show all posts
Showing posts with label string functions in Python. Show all posts

January 14, 2021

Python string functions

String Functions in Python


str="string in Python"
str1=""" a long
string with "quotes" or anything else"""
str1=input ("Please enter any string: ")
print(str)
print "hello", len("hello")

Strings are immutable, we can't change parts of string.
In Python, there is no char type, like in C++ or Java.

str[15:100]
str[-4]
str[:9]
str[1::2]
>>> str(10.3)

str1.title()
str1.upper()
str1.lower()
>>> str1.capitalize()
str1.islower()
str1.isdigit()
str1.isalpha()
str1.count('s')
str1.replace('t','s')
str1.find("i")
str1.find(".",8)

str1.split(",")
str1.split("/")[3]
str1.split("/")[-1].split(".")[-1]
str.split(sep=None, maxsplit=-1)
fields = date_string.split()
print ' '.join(fields[1:5])
str1.strip()
str1.rstrip()
str1.rstrip(";")
str1.lstrip()
line.strip(',')
line.strip().split()
for i in 'abcd'[::-1]: print(i)            # to print reverse of Python string

str1.ljust()
str1.rjust()
str.format()
print("My age is {1} and weight is {0} kgs.".format("35","65"))
str.center(width[, fillchar ])
>>> myName.center(10)
str.startswith(prefix[, start[, end ] ])
str.endswith(suffix[, start[, end ] ])
str.index("z")
str.translate(None,"012356789")
s = ustring.encode('utf-8')
t = unicode(s, 'utf-8') 

>>> 'Hi %s, I have %d rupees' % ('Thirumani', 44)

Operators plus (+) and multiplication (*) can be used on strings, in Python.
txt = "hello" + "world"
str2 + str4
"string" * 4
'satya' * 23

Related Python Articles:  File Handling in Python          Python Interview Questions