Posts

String operations in Python

avatar of @filler
25
0 views
·
2 min read
CODEOUTPUT
astring = "Hello Steem!"
print(astring.upper())HELLO STEEM!

I used the markdown table generator to create the table for this.

Look how easy it is to get output by inserting a small bit of code.

CODEOUTPUT
astring = "Hello Steem!"
print(astring.lower())hello steem!

Fun string play - from exercise in learnpython.org

s = "Be cool always" #length should be 14 print("Length of s = %d" % len(s))

#first occurrence of "a" should be at index 8 print("The first occurrence of the letter a = %d" % s.index("a"))

#number of a's should be 2 print("a occurs %d times" % s.count("a"))

#slicing the string into bits print("The first five characters are '%s'" % s[:5]) # Start to 5 print("The next five characters are '%s'" % s[5:10]) # 5 to 10 print("The thirteenth character is '%s'" % s[12]) # Just number 12 print("The characters with odd index are '%s'" %s[1::2]) #(0-based indexing) print("The last five characters are '%s'" % s[-5:]) # 5th-from-last to end

#convert everything to uppercase print("String in uppercase: %s" % s.upper())

#convert everything to lowercase print("String in lowercase: %s" % s.lower())

#check how a string starts if s.startswith("Be"): print("String starts with 'Be'. Good!")

#check how a string ends if s.endswith("ays!"): print("String ends with 'ays!'. Good!")

#split the string into three separate strings, #each containing only a word print("Split the words of the string: %s" % s.split(" "))

output

Length of s = 14 The first occurrence of the letter a = 8 a occurs 2 times The first five characters are 'Be co' The next five characters are 'ol al' The thirteenth character is 'y' The characters with odd index are 'eco las' The last five characters are 'lways' String in uppercase: BE COOL ALWAYS String in lowercase: be cool always String starts with 'Be'. Good! Split the words of the string: ['Be', 'cool', 'always']

image source - python.org logo and google colab screenshot