Strings in Python for Beginners

A string is a data type used for handling text. To create a string in Python, use single or double quotes. For multi-line strings, use triple quotes (either single or double).

first = 'Hello, world!'
second = "Hello, world!"
third = """By the seashore stands a green oak,
a golden chain on that oak."""

It would be dull if all strings in a program were only created in the source code. Fortunately, Python has a function called input. With it, you can get a string from the user.

name = input('Enter your name')
greeting = "Hello, " + name
print(greeting)

When you run this program, the user is prompted to enter their name. Once they do, by typing on the keyboard and pressing “Enter,” the entered name is stored in the variable name.

In the second line of the program, there is a familiar operator +. It is used to join two strings into one. In programming, this joining is called concatenation.

The third line displays the greeting and the name on the screen. So, if the user enters the name “Vasiliy,” the screen will display:

Hello, Vasiliy

Strings can be empty, meaning they do not contain any characters. A space is a character like any other, and these two strings are not equal.

a = ""   # empty string
b = " "  # string consisting of a single space

To get the length of a string, use the built-in Python function len. This program, for example, displays the length of the text entered by the user.

string = input('Enter any text')
a = len(string)
print(a)