THE WORLD'S LARGEST WEB DEVELOPER SITE

Python Strings


String Literals

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.

Example

Get the character at position 1 (remember that the first character has the position 0):

a = "Hello, World!"
print(a[1])
Run example »

Example

Substring. Get the characters from position 2 to position 5 (not included):

b = "Hello, World!"
print(b[2:5])
Run example »

Example

The strip() method removes any whitespace from the beginning or the end:

a = " Hello, World! "
print(a.strip()) # returns "Hello, World!"
Run example »

Example

The len() method returns the length of a string:

a = "Hello, World!"
print(len(a))
Run example »

Example

The lower() method returns the string in lower case:

a = "Hello, World!"
print(a.lower())
Run example »

Example

The upper() method returns the string in upper case:

a = "Hello, World!"
print(a.upper())
Run example »

Example

The replace() method replaces a string with another string:

a = "Hello, World!"
print(a.replace("H", "J"))
Run example »

Example

The split() method splits the string into substrings if it finds instances of the separator:

a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!']
Run example »


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 the screen:

Example

demo_string_input.py

print("Enter your name:")
x = input()
print("Hello, ", x)

Save this file as demo_string_input.py, and load it through the command line:

C:\Users\Your Name>python demo_string_input.py

Our program will prompt the user for a string:

Enter your name:

The user now enters a name:

Linus

Then, the program prints it to screen with a little message:

Hello, Linus

Test Yourself With Exercises

Exercise:

Use the len method to print the length of the string.

x = "Hello World"
print()

Start the Exercise