Language: EN

tipo-string-en-python

The String Type in Python

In Python, strings (str) are immutable sequences of Unicode characters. They are used to represent text and are surrounded by single ' or double " quotes.

Strings in Python can be declared in several ways:

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.

Additionally, they are internally represented as sequences of Unicode characters, so we can use special characters and those specific to certain languages without issues.

Special Characters

Strings in Python support special characters to represent newlines (\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 various basic operations and manipulations with text strings:

String Concatenation

String concatenation is done 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 (exclusive)
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 = "John"
age = 30
message = "Hello, my name is {} and I am {} years old.".format(name, age)
print(message)  # Output: "Hello, my name is John 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 John and I am 30 years old."

Useful Methods

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

Verification 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()
trimmed_text = text.strip()
print(uppercase_text)  # Output: "   HELLO, WORLD!   "
print(trimmed_text)  # Output: "Hello, world!"

Transformation Methods

  • split(separator): Splits the string into a list of substrings separated by the specified separator.
  • join(iterable): Joins 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?"