String literals in python are surrounded by either single quotation marks, or double quotation marks.
'hello' is the same as "hello".
Strings can be output to screen using the print function. For example: print("hello").
Like many other popular programming languages, strings in Python are arrays of bytes representing unicode characters. However, Python does not have a character data type, a single character is simply a string with a length of 1. Square brackets can be used to access elements of the string.
Get the character at position 1 (remember that the first character has the position 0):
Substring. Get the characters from position 2 to position 5 (not included):
The strip() method removes any whitespace from the beginning or the end:
print(a.strip()) # returns "Hello, World!"
The len() method returns the length of a string:
The lower() method returns the string in lower case:
The upper() method returns the string in upper case:
The replace() method replaces a string with another string:
The split() method splits the string into substrings if it finds instances of the separator:
print(a.split(",")) # returns ['Hello', ' World!']
Command-line String Input
Python allows for command line input.
That means we are able to ask the user for input.
The following example asks for the user's name, then, by using the
input() method, the program prints the name to
x = input()
print("Hello, " + x)
Save this file as demo_string_input.py, and load it through the command line:
Our program will prompt the user for a string:
The user now enters a name:
Then, the program prints it to screen with a little message: