Python. Strings. General concepts. String declaration. Operations with strings. Examples

Strings. General concepts. String declaration. Operations with strings. Examples


Search other websites:

1. String declaration. The purpose of strings

In the Python programming language, a string is a built-in type that is designed to store and present character or text information in an ordered manner. From a syntactic point of view, a string is a sequence of characters taken in single or double quotes.

Strings provide the use of everything that can be represented in text form, for example:

  • information in files;
  • data on names, descriptions, comments in databases;
  • Internet domain names;
  • information texts in documents that support Unicode encoding;
  • other.

Strings belong to a class of objects called sequences. String literals taken in single or double quotation marks are interchangeable, that is, this is an object of the same type.

Examples of literal strings.

"Hello world!"
"I'm" # I'm a string - single quotes in double quotes
'I"m' # I'm a string - double quotes in single quotes


2. What string types are supported in Python?

Python supports three types of strings:

  • strings of type str – intended to represent text in Unicode format and other coding systems. This format contains ASCII characters and characters in other encodings;
  • bytes strings – intended to represent binary data;
  • strings of type bytearray – intended to represent binary data, taking into account changes in the type of bytes.

Python 2.6 uses the unicode type to represent Unicode text.


3. How to declare a variable of type “string“? General form

To declare a variable of type string, just use the assignment operator =. The general form of variable declaration is as follows

variable_name = string


  • variable_name – a name for the variable. In the future, this name is used in the program and is associated with the string;
  • string – string (literal), taken in single or double quotes.


4. Examples of declaring string variables


a = 'abcde' # single quote declaration
b = "abcde" # double quute declaration
line = '' # empty string
block_s = """abcde""" # triple quote block
s1 = b'hello' # byte string in versions 3.0 and later
s2 = u'hello' # string with Unicode characters
s3 = 's\np\ta\x00m' # escape sequences
s4 = r'c:\myfolder\myfile1.txt' # unformatted string


5. Is there a type in Python that describes a single character (e.g. char)?

No, there is not. To describe a single character, the same string is used, which contains only one character (single-character string), for example:

firstLetter = 'A'
lastLetter = 'Z'
zero = '0'


6. Basic operators for working with strings. Table

It is possible perform typical operations on strings. To do this, the corresponding operators are overloaded in Python.

The table below lists the operators for working with strings.


Use in programs Explanation
+ s1+s2 Concatenation
* s*2 Reiteration
[ ] s[i] Access to the character in string s at index i
[:] s[i:j] Pulling a substring from position i to position j


7. An example of using the operator + concatenation of strings

The concatenation or addition operator is indicated by the + symbol. The operator can be used in expressions of varying complexity.


# Concatenation
s1 = 'Hello'
s2 = 'world!'
s3 = s1 + ' ' + s2 # s3 = 'Hello world!'


8. Example of using the operator * of string repeating

The operator of string repetition is denoted by *. The operator forms a new string object, which is repeated a specified number of times.

Example. In the example, string s2 is equal to three lines s1

# Operator * of string repetition
s1 = 'abc'
s2 = s1*3 # 'abcabcabc'


9. An example of using the [] operator to pull a string item by its index

To get a single character in a string, the index operation [] is used. The following are examples of getting a string character by its index. The numbering starts with index 0.

Example. In the example, the variable c is assigned a character with index [1] of string s.

# Operator [] - pulling a character in a string by its index
s1 = 'abc'
c = s1[1] # c = 'b'


10. An example of using the [:] operator to extract a substring from a string

The [:] operator is used to process substrings in strings. This operator has many varieties. For more information about the operator [:] is described here. This topic provides some limited examples of using the operator to extract a string from a substring.


# Operator [:] - take a character in a string by index
s1 = '01234567890'
s2 = s1[2:4] # s2 = '23'
s3 = s1[:5] # s3 = '01234'
s4 = s1[:-1] # s4 = '0123456789'


11. Example of string traversal using the for loop statement

The example shows how to view all characters in a string using the for loop statement. The problem of viewing the number of characters ‘z’ in a string is solved. The string is entered from the keyboard.

# Strings
# Example of traversing string items in a loop

# 1. Input string
s = str(input("Enter string: "))

# 2. Display string for checking
for c in s:
    print(c, end=' ') # characters output

# 3. Determining the number of characters 'z' in a string
count = 0;
for c in s:
    if c=='z':
        count = count+1

# Display the result
print("count = ", count)

The result of the program

Enter string: zero z1sdlkj 12+laksd
z e r o   z 1 s d l k j   1 2 + l a k s d
count = 2


12. Comparison of strings. Figure. Examples

Strings can be compared with each other using comparison operations >, <, >=, <=, ==, !=.

The strings are compared according to the following rules (Figure 1):

  1. The direction of comparison is from left to right;
  2. Strings are compared character by character. The codes of the corresponding symbols are compared;
  3. String comparison ends when one of the following conditions is met:
    • the equality of codes is violated;
    • one of the lines ends;
    • both lines are terminated.

Python. Strings comparison

Figure 1. Strings comparison: a) strings of different lengths; b) strings of the same length

Two strings are considered equal if their length is the same and they match character by character (Figure 2).

Python. An example of identical strings

Figure 2. An example of identical strings. String s1 is equal to string s2

Example. The example demonstrates inputting strings and outputting the result of their comparison.

# Input strings for comparison
s1 = input("s1 = ")
s2 = input("s2 = ")

# Comparing strings and displaying the result
if s1>s2:
    print("s1 > s2")
elif s1==s2:
    print("s1 == s2")
    print("s1 < s2")


13. An example of using the in operator for a string

The example determines the presence of a character in a string and a substring in a string.

# The in operation for strings.
# Determine if character 'n' is in string
s = 'Transformation'

if 'n' in s:

# Determine if substring 'fo' is present in string
if "fo" in s:


Related topics