Basic String Operations in Python

#Basic_String_Operations
# <<---this is a comment

#can use double or single quotes"
astring = "Hello world!"
astring2 = 'Hello world!'

#enclose single quotes inside double quotes
print("single quotes are ' '")

#print the length of a string
print(len(astring))

#print index of string w/ first occurrence of the letter #"o"
print(astring.index("o"))

#count the number of "ls" in a string
print(astring.count("l"))

#output slice of string from index 3 to 6 (
always one less from end number specified)
print(astring[3:7])

#print slice of string from index 3 to 6 w/ step of 1
print(astring[3:7:1])

#reverse a string
print(astring[::-1])

#convert string to all uppercase characters
print(astring.upper())

#convert string to all lowercase characters
print(astring.lower())

print(astring.startswith("Hello"))  #returns true if #true
print(astring.endswith("blah")) #returns false

#create a list with words of the string separated by a #space
afewwords = astring.split(" ")

Leave a comment

Design a site like this with WordPress.com
Get started