Language: EN

tipo-string-en-python

The String Type in Python

In Python, strings (str) are immutable sequences of Unicode characters used to represent text.

Strings in Python can be declared in several ways, enclosing them in single ' or double " quotes.

simple_string = 'Hello, world!'
double_string = "Hello, world!"
triple_string = """This is an example
of a string with multiple lines."""

Strings in Python are immutable (which means they cannot be modified once created). Any operation that seems to modify a string actually creates a new string.

Internally, they are represented as sequences of Unicode characters. Therefore, we can safely use special characters or those specific to certain languages.

Special characters

Strings in Python support special characters to represent new lines (\n), tabs (\t), quotes within strings (\", \'), among others.

string_with_newline = "First line\nSecond line"
print(string_with_newline)
# Output:
# First line
# Second line

String operations

Python supports several basic operations and manipulations with text strings:

String concatenation

String concatenation is performed using the + operator:

string1 = "Hello"
string2 = " world"
concatenated_string = string1 + string2
print(concatenated_string)  # Output: "Hello world"

Indexing and slicing

It is possible to access individual characters of a string using indices and slice (slicing) to obtain substrings:

message = "Hello world"
first_character = message[0]
substring = message[1:5]  # From index 1 to 5 (not inclusive)
print(first_character)  # Output: "H"
print(substring)  # Output: "ello"

Formatting methods

Python offers several methods for formatting strings, such as format() and formatted string literals (f-string):

name = "Luis"
age = 30
message = "Hello, my name is {} and I am {} years old.".format(name, age)
print(message)  # Output: "Hello, my name is Luis and I am 30 years old."

# F-string (python 3.6+)
fstring_message = f"Hello, my name is {name} and I am {age} years old."
print(fstring_message)  # Output: "Hello, my name is Luis and I am 30 years old."

Useful methods

In addition to basic string manipulation methods, Python offers specialized methods to check and transform strings:

Checking methods

  • startswith(prefix): Returns True if the string starts with the given prefix.
  • endswith(suffix): Returns True if the string ends with the given suffix.
  • isalpha(): Returns True if all characters in the string are letters.
  • isdigit(): Returns True if all characters in the string are digits.
string = "Python is awesome"
print(string.startswith("Py"))  # Output: True
print(string.endswith("me"))  # Output: True
print(string.isalpha())  # Output: False (because there are spaces and not just letters)

Manipulation methods

Python provides numerous methods to manipulate strings, such as upper(), lower(), strip(), replace(), split(), among others:

text = "   Hello, world!   "
uppercase_text = text.upper()
text_without_spaces = text.strip()
print(uppercase_text)  # Output: "   HELLO, WORLD!   "
print(text_without_spaces)  # Output: "Hello, world!"

Transformation methods

  • split(separator): Splits the string into a list of substrings separated by the specified separator.
  • join(iterable): Joins the elements of an iterable (like a list) into a single string using the string as a separator.
text = "Hello, how are you?"
words = text.split(", ")
print(words)  # Output: ['Hello', 'how are you?']

list_of_words = ['Hello', 'how', 'are', 'you?']
joined_text = ' '.join(list_of_words)
print(joined_text)  # Output: "Hello how are you?"