Tuesday, April 9, 2019

Python String Operations With Examples




Python String operations



capitalize() Converts the first character to upper case



>>> txt = "hello, and welcome to my world."



>>> y=txt.capitalize()



>>> print(y)



Hello, and welcome to my world.



casefold() Converts string into lower case



>>> txt = "Hello, And Welcome To My World!"



>>> x = txt.casefold()



>>> print(x)



hello, and welcome to my world!



center() Returns a centered string



>>> txt = "banana"



>>> x = txt.center(20)



>>> print(x)



       banana



>>> txt = "banana"



>>> x = txt.center(20, "O")



>>> print(x)



OOOOOOObananaOOOOOOO







count() Returns the number of times a specified value occurs in a string



>>> txt = "I love apples, apple are my favorite fruit"



>>> x = txt.count("apple")



>>> print(x)



2



>>> txt = "I love apples, apple are my favorite fruit"



>>> x = txt.count("apple", 10, 24)



>>> print(x)



1







encode() Returns an encoded version of the string



>>> txt = "My name is Ståle"



>>> x = txt.encode()



>>> print()



>>> print(x)



b'My name is St\xc3\xa5le'



endswith() Returns true if the string ends with the specified value



>>> txt = "Hello, welcome to my world."



>>> x = txt.endswith("my world.")



>>> print(x)



True



>>> txt = "Hello, welcome to my world."



>>> x = txt.endswith("my world.", 5, 11)



>>> print(x)



False



expandtabs() Sets the tab size of the string



>>> txt = "H\te\tl\tl\to"



>>> print(txt)



H       e       l       l       o



>>> print(txt.expandtabs())



H       e       l       l       o



>>> print(txt.expandtabs(2))



H e l l o



>>> print(txt.expandtabs(4))



H   e   l   l   o



>>> print(txt.expandtabs(10))



H         e         l         l         o



find() Searches the string for a specified value and returns the position of where it was found



>>> x = txt.find("welcome")



>>> print(x)



7



>>> txt = "Hello, welcome to my world."



>>> x = txt.find("e")



>>> print(x)



1



>>> txt = "Hello, welcome to my world."



>>> print(txt.find("q"))



-1



>>> print(txt.index("q"))



Traceback (most recent call last):



  File "", line 1, in



ValueError: substring not found







index() Searches the string for a specified value and returns the position of where it was found



>>> txt = "Hello, welcome to my world."



>>> x = txt.index("welcome")



>>> print(x)



7



>>> txt = "Hello, welcome to my world."



>>> print(txt.find("q"))



-1



>>> print(txt.index("q"))



Traceback (most recent call last):



  File "", line 1, in



ValueError: substring not found







isalnum() Returns True if all characters in the string are alphanumeric



>>> txt = "Company12"



>>> x = txt.isalnum()



>>> print(x)



True



>>> txt = "Company 12"



>>> x = txt.isalnum()



>>> print(x)



False



isalpha() Returns True if all characters in the string are in the alphabet



>>> txt = "CompanyX"



>>> x = txt.isalpha()



>>> print(x)



True



>>> txt = "Company10"



>>> x = txt.isalpha()



>>> print(x)



False



isdecimal() Returns True if all characters in the string are decimals



>>> txt = "\u0033" #unicode for 3



>>> x = txt.isdecimal()



>>> print(x)



True



>>> a = "\u0030" #unicode for 0



>>> b = "\u0047" #unicode for G



>>> print(a.isdecimal())



True



>>> print(b.isdecimal())



False



isdigit() Returns True if all characters in the string are digits



>>> txt = "50800"



>>> x = txt.isdigit()



>>> print(x)



True



>>> a = "\u0030" #unicode for 0



>>> b = "\u00B2" #unicode for ²



>>> print(a.isdigit())



True



>>> print(b.isdigit())



True







isidentifier() Returns True if the string is an identifier



>>> txt = "Demo"



>>> x = txt.isidentifier()



>>> print(x)



True



>>> a = "MyFolder"



>>> b = "Demo002"



>>> c = "2bring"



>>> d = "my demo"



>>> print(a.isidentifier())



True



>>> print(b.isidentifier())



True



>>> print(c.isidentifier())



False



>>> print(d.isidentifier())



False



islower() Returns True if all characters in the string are lower case



>>> txt = "hello world!"



>>> x = txt.islower()



>>> print(x)



True



>>> a = "Hello world!"



>>> b = "hello 123"



>>> c = "mynameisPeter"



>>> print(a.islower())



False



>>> print(b.islower())



True



>>> print(c.islower())



False



isnumeric() Returns True if all characters in the string are numeric



>>> txt = "565543"



>>> x = txt.isnumeric()



>>> print(x)



True



>>> a = "\u0030" #unicode for 0



>>> b = "\u00B2" #unicode for ²



>>> c = "10km2"



>>> print(a.isnumeric())



True



>>> print(b.isnumeric())



True



>>> print(c.isnumeric())



False



isprintable() Returns True if all characters in the string are printable



txt = "Hello! Are you #1?"



>>> x = txt.isprintable()



>>> print(x)



True



>>> txt = "Hello!\nAre you #1?"



>>> x = txt.isprintable()



>>> print(x)



False



isspace() Returns True if all characters in the string are whitespaces



>>> txt = "   "



>>> x = txt.isspace()



>>> 



>>> print(x)



True



>>> txt = "   s   "



>>> x = txt.isspace()



>>> print(x)



False



istitle() Returns True if the string follows the rules of a title



>>> txt = "Hello, And Welcome To My World!"



>>> x = txt.istitle()



>>> print(x)



True



>>> a = "HELLO, AND WELCOME TO MY WORLD"



>>> b = "Hello"



>>> c = "22 Names"



>>> d = "This Is %'!?"



>>> print(a.istitle())



False



>>> print(b.istitle())



True



>>> print(c.istitle())



True



>>> print(d.istitle())



True



isupper() Returns True if all characters in the string are upper case



>>> txt = "THIS IS NOW!"



>>> x = txt.isupper()



>>> print(x)



True



>>> a = "Hello World!"



>>> b = "hello 123"



>>> c = "MY NAME IS PETER"



>>> print(a.isupper())



False



>>> print(b.isupper())



False



>>> print(c.isupper())



True



join() Joins the elements of an iterable to the end of the string



>>> myTuple = ("John", "Peter", "Vicky")



>> x = "#".join(myTuple)



>>> print(x)



John#Peter#Vicky



>>> myDict = {"name": "John", "country": "Norway"}



>>> mySeparator = "TEST"



>>> x = mySeparator.join(myDict)



>>> print(x)



nameTESTcountry



ljust() Returns a left justified version of the string



>>> txt = "banana"



>>> x = txt.ljust(20)



>>> print(x, "is my favorite fruit.")



banana               is my favorite fruit.



>>> txt = "banana"



>>> x = txt.ljust(20, "O")



>>> print(x)



bananaOOOOOOOOOOOOOO



lower() Converts a string into lower case



>>> txt = "Hello my FRIENDS"



>>> x = txt.lower()



>>> print(x)



hello my friends



lstrip() Returns a left trim version of the string



>>> txt = "     banana     "



>>> x = txt.lstrip()



>>> print("of all fruits", x, "is my favorite")



of all fruits banana      is my favorite



>>> txt = ",,,,,ssaaww.....banana"



>>> x = txt.lstrip(",.asw")



>>> print(x)



Banana



partition() Returns a tuple where the string is parted into three parts



>>> txt = "I could eat bananas all day"



>>> x = txt.partition("bananas")



>>> print(x)



('I could eat ', 'bananas', ' all day')



>>> txt = "I could eat bananas all day"



>>> x = txt.partition("apples")



>>> print(x)



('I could eat bananas all day', '', '')



replace() Returns a string where a specified value is replaced with a specified value



I could eat apples all day



>>> txt = "one one was a race horse, two two was one too."



>>> x = txt.replace("one", "three")



>>> print(x)



three three was a race horse, two two was three too.



>>> txt = "one one was a race horse, two two was one too."



>>> x = txt.replace("one", "three", 2)



>>> print(x)



three three was a race horse, two two was one too.



rfind() Searches the string for a specified value and returns the last position of where it was found



>>> txt = "Mi casa, su casa."



>>> x = txt.rfind("casa")



>>> print(x)



12



>>> txt = "Hello, welcome to my world."



>>> x = txt.rfind("e")



>>> print(x)



13



>>> txt = "Hello, welcome to my world."



>>> x = txt.rfind("e", 5, 10)



>>> print(x)



8



>>> txt = "Hello, welcome to my world."



>>> print(txt.rfind("q"))



-1



>>> print(txt.rindex("q"))



Traceback (most recent call last):



  File "", line 1, in



ValueError: substring not found



>>> 



rindex()Searches the string for a specified value and returns the last position of where it was found



>>> txt = "Mi casa, su casa."



>>> x = txt.rindex("casa")



>>> print(x)



12



>>> txt = "Hello, welcome to my world."



>>> x = txt.rindex("e")



>>> print(x)



13



>>> txt = "Hello, welcome to my world."



>>> x = txt.rindex("e", 5, 10)



>>> print(x)



8



>>> txt = "Hello, welcome to my world."



>>> print(txt.rfind("q"))



-1



>>> print(txt.rindex("q"))



Traceback (most recent call last):



  File "", line 1, in



ValueError: substring not found



rjust() Returns a right justified version of the string



>>> txt = "banana"



>>> x = txt.rjust(20)



>>> print(x, "is my favorite fruit.")



              banana is my favorite fruit.



>>> txt = "banana"



>>> x = txt.rjust(20, "O")



>>> print(x)



OOOOOOOOOOOOOObanana



rpartition() Returns a tuple where the string is parted into three parts



>>> txt = "I could eat bananas all day, bananas are my favorite fruit"



>>> x = txt.rpartition("bananas")



>>> print(x)



('I could eat bananas all day, ', 'bananas', ' are my favorite fruit')



>>> txt = "I could eat bananas all day, bananas are my favorite fruit"



>>> x = txt.rpartition("apples")



>>> print(x)



('', '', 'I could eat bananas all day, bananas are my favorite fruit')



rsplit() Splits the string at the specified separator, and returns a list



>>> txt = "apple, banana, cherry"



>>> x = txt.rsplit(", ")



>>> print(x)



['apple', 'banana', 'cherry']



>>> txt = "apple, banana, cherry"



>>> # setting the max parameter to 1, will return a list with 2 elements!



... x = txt.rsplit(", ", 1)



>>> print(x)



['apple, banana', 'cherry']



rstrip() Returns a right trim version of the string



>>> txt = "     banana     "



>>> x = txt.rstrip()



>>> print("of all fruits", x, "is my favorite")



of all fruits      banana is my favorite



>>> txt = "banana,,,,,ssaaww....."



>>> x = txt.rstrip(",.asw")



>>> print(x)



Banan



split() Splits the string at the specified separator, and returns a list



>>> txt = "welcome to the jungle"



>>> x = txt.split()



>>> print(x)



['welcome', 'to', 'the', 'jungle']



>>> txt = "hello, my name is Peter, I am 26 years old"



>>> x = txt.split(", ")



>>> print(x)



['hello', 'my name is Peter', 'I am 26 years old']



>>> txt = "apple#banana#cherry#orange"



>>> x = txt.split("#")



>>> print(x)



['apple', 'banana', 'cherry', 'orange']



>>> txt = "apple#banana#cherry#orange"



>>> # setting the max parameter to 1, will return a list with 2 elements!



... x = txt.split("#", 1)



>>> print(x)



['apple', 'banana#cherry#orange']



splitlines() Splits the string at line breaks and returns a list



>>> txt = "Thank you for the music\nWelcome to the jungle"



>>> x = txt.splitlines()



>>> print(x)



['Thank you for the music', 'Welcome to the jungle']



>>> txt = "Thank you for the music\nWelcome to the jungle"



>>> x = txt.splitlines(True)



>>> print(x)



['Thank you for the music\n', 'Welcome to the jungle']



startswith() Returns true if the string starts with the specified value



>>> txt = "Hello, welcome to my world."



>>> x = txt.startswith("Hello")



>>> print(x)



True



>>> txt = "Hello, welcome to my world."



>>> x = txt.startswith("wel", 7, 20)



strip() Returns a trimmed version of the string



>>> txt = "     banana     "



>>> x = txt.strip()



>>> print("of all fruits", x, "is my favorite")



of all fruits banana is my favorite



>>> txt = ",,,,,rrttgg.....banana....rrr"



>>> x = txt.strip(",.grt")



>>> print(x)



Banana



swapcase() Swaps cases, lower case becomes upper case and vice versa



>>> txt = "Hello My Name Is PETER"



>>> x = txt.swapcase()



>>> print(x)



hELLO mY nAME iS peter



title() Converts the first character of each word to upper case



>>> txt = "Welcome to my world"



>>> x = txt.title()



>>> print(x)



Welcome To My World



>>> txt = "Welcome to my 2nd world"



>>> x = txt.title()



>>> print(x)



Welcome To My 2Nd World



>>> txt = "hello b2b2b2 and 3g3g3g"



>>> x = txt.title()



>>> print(x)



Hello B2B2B2 And 3G3G3G



upper() Converts a string into upper case



>>> txt = "Hello my friends"



>>> x = txt.upper()



>>> print(x)



HELLO MY FRIENDS



zfill() Fills the string with a specified number of 0 values at the beginning+



>>> txt = "50"



>>> x = txt.zfill(10)



>>> print(x)



0000000050



>>> a = "hello"



>>> b = "welcome to the jungle"



>>> c = "10.000"



>>> print(a.zfill(10))



00000hello



>>> print(b.zfill(10))



welcome to the jungle



>>> print(c.zfill(10))



000010.000


No comments:

Post a Comment

Python Challenges Program

Challenges program: program 1: #Input :ABAABBCA #Output: A4B3C1 str1="ABAABBCA" str2="" d={} for x in str1: d[x]=d...