The name str in Python is used to refer to strings. It is a built-in data type that represents ordered sequences of Unicode characters. Typically, strings contain textual information. They are similar to C arrays, but have a number of powerful processing features.
There are several ways to write strings. The most popular are quotation marks and apostrophes. They are interchangeable and use them to eliminate the backslash character "\":
>>>Example_1="This is how lines are written"
Three quotes are also allowed when processing strings in Python. It is convenient to enclose large blocks of text in them. Apostrophes and regular quotes can be present inside the construction:
>>>Example_2=""Approximate set of words for a 'block string' in Python"""
Strings support the pressure of standard operations for sequences. These are concatenation, indexing, slice extraction, length calculation and repetition:
- >>>Str_1="FB" Assign value
- >>>Str_2=Str_1 + "." + "ru"perform concatenation
- >>>Str_3="O"3 + "PS!" repetition and concatenation
- >>>len(Page_3) length calculation
Because str are immutable types in Python, each operation creates a new string object.
Each element of a string can be accessed by its position or sequence number. The countdown does not start from the usual unit, but from zero. To work with indices, square brackets are used. Therefore, if you want to extract the second character, you need to pass the command “object name” to the interpreter:
When extracting a slice, the number to the left of the ":" operator means the left border inclusive. The number on the right indicates the element up to which the slice will be extracted. It is important to remember that the object specified to the right of the colon is not included in the slice:
In Python, str() can be called as a built-in function. It takes any objects as an argument and returns their string representation. For example, if you need to concatenate, both sides of the "+" sign must have the same type of data. Otherwise, the interpreter will issue an error message:
- >>>5+ "dogs" + "run"
- Traceback (most recent call last): … TypeError
- >>>str(5) + " dogs " + " run."
- "5 dogs run."
A different repr() function is allowed instead of str(). It also performs the conversion, but returns the object as a line of code in an expanded form.
For deep processing of strings, there is a powerful set of methods specific to this data type. Formally, these are attributes attached to objects that refer to functions.
Syntactically, the construction of using string methods is as follows: "object.method(argument)".
- >>>l.replace("ff", "gg")
The example used the.replace() method of replacing elements. This generic method accepts strings of any length as arguments and performs a global search followed by a replacement.
There are other methods and operators for working with strings, formatting and converting them. A complete list is in the official language guide.