Py03: String

A string is used to store text rather than numbers in a program. A string is data that contains a sequence of characters that are used to display or as a communication tool.

Introduction

A string in Python is a sequence of characters enclosed in single or double quotes. A string variable is created by assigning string literals to a variable. String literal is the character sequence surrounded by the quote sign.

str1 = 'Python is new for me'
str2 = "But looks fun"

A string containing a single quote should be included inside a double quote. and vice versa. The following string will display the single quote on the screen.

str = "The 'color' is red"
print(str)

Output

The 'color' is red
> 

Use triple quote (""") or (''') for multiple line string, this is known as docstring. This is similar to <pre> tag in HTML.

stringName = '''
string line 1
string line 2
string line 3
'''

The following example shows how this string is declared and printed:

infoStr = '''
a cat jump over the dog
    dog sleeps on the rug
         rug is placed on doorway
'''
print(infoStr)

Output

a cat jump over the dog
    dog sleeps on the rug
         rug is placed on doorway

> 

Concatenating strings

To join two strings to form a single string. To concatenate strings in Python we can use + (plus). The following example shows this. (the hash show preview of output)

str1 = "teacher"
str2 = "cube"

newString = str1 + str2
print("Output:", newString)     # teachercube

Output

Output: teachercube
> 

Alternatively, we can perform Concatenating of string simply by placing two strings literal beside each other. This does not work for concatenating strings stored in variables. The following example produces the same output as the previous example.

str = "teacher""cube"
print("Output", str)       # teachercube

Accessing string element

String elements can be accessed using index numbers. The first letter starts with 0. An index is specified using square brackets [ and ].

stringName[index]

The following example shows using an index to access an element of a character in the string. (the hash show preview of output)

str = "teachercube"

print("Original         : ", str)      # teachercube
print("first element    : ", str[0])   # t
print("fifth element    : ", str[4])   # h
print("last element     : ", str[-1])  # e
print("3rd last element : ", str[-3])  # u

Index 0 (zero) refers to the first character. To refer to the fifth element index is 4 (four) because (5 - 1 = 4). Python allows negative numbers, which means starting indexing from the back of the string. Index -1 is the last character, -2 is the second last, and so on.

Finding String Length

The length of the string can be obtained using the len() function. It returns the number of characters in a string.

len(stringName)

The following example shows how len() is used to get the length of the string (the hash show preview of the output)

str = 'teachercube'

print("Text : ", str)       # Text : teachercube
print("Length :", len(str)) # Lenght : 11

Output

Text : teachercube
Lenght : 11
>

Slicing the string

To get a portion of the string is called slicing. Slicing is done by providing index values in a square bracket ([]).

stringName[start:end]

The start and end parameters are optional. By default, the start is 0, and the end by default length of the string. this will return a string from start to end-1.

str = 'teachercube'

print(str[3:7])     # cher
print(str[5:-2])    # ercu
print(str[0:-8])    # tea

Output

cher
ercu
tea
>

A string is immutable. Element values of a string cannot be changed. The following example shows an attempt to change the value of the first element. This will produce an error.

str = 'teachercube'

str[0] = 'a'

Output

Traceback (most recent call last):
  File "<string>", line 4, in <module>
TypeError: 'str' object does not support item assignment

To check if the character or substring is in the string, use the in operator. To check if the character or substring is not in the string using the not in operator.

str = "teachercube"

print('a' in str)        # true
print('z' in str)        # false
print('z' not in str)    # true
print('e' not in str)    # false
print('cher' in str)     # true

Input from user

To add interactivity we can allow a program to take input from the user. Python provides the input() function. The syntax is:

inputStr = input(prompt_message)

The prompt_messange is a text we want to display on the screen. The text is a piece of information for the user to enter correct input. After the user enters input and presses enter, this function returns a string.

Example

name = input("Enter you name: ")
print("Hi,",name)

Output

Enter you name: Civa
Hi, Civa
> 

Casting

Casting is used to specify the type of variable we want to create. The str() constructor creates a string from string literals, an integer literal, or float literals.

a = str("24.12") # '24.12'
print("a is ", type(a))
print(a)

b = str(43)     # '43'
print("b is ", type(b))
print(b)

c = str(1.73)   # '1.73'
print("c is ", type(c))
print(c)

Output

a is  <class 'str'>
24.12
b is  <class 'str'>
43
c is  <class 'str'>
1.73
> 

A post by Cuber

Comments

Popular posts from this blog

Drawing Simple Pie Chart

VB.net connecting to SQL Server

VB.net