Sunday, September 1, 2019

Python tutorial 2 | Handling Strings

This is the second of Python Tutorials for Beginners. In order to get started, please first see the Python Tutorial 1 | Introduction. Let us learn how to handle strings in Python programming language. Please view my Python video tutorial 2 or read on...

A string is a sequence of characters. A string is enclosed by single quotes or double quotes. A multi-line string is enclosed by triple quotes (either both single quotes or both double quotes). You can see your string by using the print function. The print function omits enclosing quotes. The + Python string operator concatenates (combines) strings. The * Python string operator repeats a string a number of times. You can assign multiple variables in a single Python statement. Using indexing, you can extract a single character from a string. Using slicing, you can extract any part of a string. Strings in Python programming language are immutable. This means that once you define a string, you cannot change it. Now, let us see examples of these concepts.

You can try the Python commands at the Python prompt. Note that comments follow the # symbol (they are only for your understanding).
>>> 'Hello'               # this statement just echoes the string back to you.
>>> 'Hello'               # same as the previous statement but the string is within single quotes
>>> x = "John"
>>> x               # this statement echoes the value of Python variable, x, which is a string.
>>> print(x)                # this statement displays the value of x but without the quotes.
>>> y = "Its John's."   # note that the single quote is a part of the string in Python variable, y.
>>> z = """This is line 1.
This is line 2."""               # this statement defines a multi-line string.
>>> print(z)               # print the string on two different lines
>>> print("Hello" + " " + "there")               # concatenation - it combines the three strings.
>>> a = b = 'Python'               # multiple assignment - assigns the string 'Python' to both Python variables.
>>> a * 3              # echoes the string value of Python variable, a 3 times
>>> x[0]               # indexing - echoes the first character of the string value of Python variable, x
>>> x[-1]               # indexing - echoes the last character of the string value of variable x
>>> x[0:2]               # slicing - echoes the string value from index 0 up to but excluding index 2
>>> x[0] = 'R'               # TypeError because a string is immutable
>>> print(len(y))               # len is a string function. It prints the length of the string.
>>> n = input("Enter a name")               # input string function shows the prompt, accepts a string and assigns it to variable n.
>>> print(n.upper())               # print the string value in upper case

You can see such examples in action in my Python video tutorial 2. Thank you.

No comments:

Post a Comment