Python - String

Strings in Python are identified as a contiguous set of characters represented in the quotation marks. Python allows either pair of single or double quotes. Subsets of strings can be taken using the slice operator ([ ] and [:] ) with indexes starting at 0 in the beginning of the string.

The plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition operator. For example:

str = 'Hello World!'
print (str)          # Prints a complete string
print (str[0])       # Prints first character of the string
print (str[2:5])     # Prints characters starting from 3rd to 5th
print (str[2:])      # Prints string starting from 3rd character
print (str * 2)      # Prints string two times
print (str + "TEST") # Prints concatenated string
print (str[-1])      # Print last Character
print (str[:4])      # Print 1st four characters
Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST
!
Hell

Python - String Functions

len(str) - Find length

lower() - Converts a string into lower case, same as str.casefold()

upper() - Converts a string into upper case.

str.capitalize() - Converts the first character to upper case, and the rest is lower case. if the first character is a number than no change.

title() - convert the first character of every word in upper case. str.title() Note that the first letter after a non-alphabet letter is converted into a upper case letter.

count() - Returns the number of times a specified value appears in the string. str.count("a"), str.count("a", 10, 20), string.count(value, start, end).

The find() method finds the first occurrence of the specified value. The find() method returns -1 if the value is not found. str.find("e"), string.find(value, start, end)

endswith() - Returns true if the string ends with the specified value. str.endswith(".").

startswith() - Returns true if the string starts with the specified value, otherwise False. string.startswith(value, start, end) str.startswith("Hello").

expandtabs() - Sets the tab size of the string. str="a\tb\tc", str.expandtabs(2).

Exercise Question - String