Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære Strings and Text Manipulation | Working with Data Types
Practice
Projects
Quizzes & Challenges
Quizer
Challenges
/
Introduction to Python

bookStrings and Text Manipulation

Sveip for å vise menyen

Introduction to String Creation and Usage

Strings are one of the most important data types in Python. A string is a sequence of characters, such as letters, numbers, and symbols, used to represent text. In Python, strings are created by enclosing characters in single quotes ('...'), double quotes ("..."), or even triple quotes for multi-line text ('''...''' or """...""").

Creating Strings

You can create a string by assigning text to a variable:

message = 'Hello, world!'
name = "Alice"
multiline_text = '''This is a string
that spans multiple lines.'''

Using Strings

Strings can be printed, combined, and manipulated in various ways. For example:

  • Printing a string:
    print(message)  # Output: Hello, world!
    
  • Combining strings (concatenation):
    greeting = 'Hello, ' + name
    print(greeting)  # Output: Hello, Alice
    

Key Points

  • Strings are enclosed in quotes.
  • Strings can be single-line or multi-line.
  • Strings can be stored in variables and manipulated using various operations and methods.

Understanding how to create and use strings is essential for working with text data in Python. In the next sections, you'll learn more about combining strings, formatting text, and using built-in string methods.

1234567891011121314151617181920
# String Concatenation using '+' operator first_name = "Ada" last_name = "Lovelace" full_name = first_name + " " + last_name print(full_name) # String Formatting using f-strings age = 28 intro = f"Hello, my name is {full_name} and I am {age} years old." print(intro) # String Formatting using str.format() city = "London" info = "{0} was born in {1}.".format(full_name, city) print(info) # String Concatenation using join() words = ["Python", "is", "fun!"] sentence = " ".join(words) print(sentence)
copy
upper()
expand arrow

The upper() method returns a new string where all the characters are converted to uppercase.

Example:

text = "hello world"
print(text.upper())  # Output: 'HELLO WORLD'

Use this method when you need to standardize text to uppercase, such as for case-insensitive comparisons.

lower()
expand arrow

The lower() method returns a new string with all characters converted to lowercase.

Example:

text = "Hello World"
print(text.lower())  # Output: 'hello world'

This is useful for normalizing text before processing or comparison.

strip()
expand arrow

The strip() method removes any leading and trailing whitespace (spaces, tabs, newlines) from a string.

Example:

text = "  hello world  "
print(text.strip())  # Output: 'hello world'

Use strip() to clean up user input or text data.

replace()
expand arrow

The replace() method returns a copy of the string where all occurrences of a specified substring are replaced with another substring.

Example:

text = "I like cats. Cats are great!"
print(text.replace("cats", "dogs"))  # Output: 'I like dogs. Cats are great!'
print(text.replace("Cats", "Dogs"))  # Output: 'I like cats. Dogs are great!'

Note that replace() is case-sensitive.

split()
expand arrow

The split() method divides a string into a list of substrings based on a specified separator (default is whitespace).

Example:

text = "apple,banana,cherry"
print(text.split(","))  # Output: ['apple', 'banana', 'cherry']

This is helpful for parsing CSV data or breaking up sentences into words.

join()
expand arrow

The join() method takes all items in an iterable (like a list) and joins them into a single string, with a specified separator.

Example:

fruits = ["apple", "banana", "cherry"]
print(", ".join(fruits))  # Output: 'apple, banana, cherry'

Use join() to create strings from lists or other sequences.

find()
expand arrow

The find() method searches a string for a specified substring and returns the lowest index where it is found. If not found, it returns -1.

Example:

text = "hello world"
print(text.find("world"))  # Output: 6
print(text.find("Python"))  # Output: -1

Use find() to locate substrings within a string.

startswith() and endswith()
expand arrow

The startswith() and endswith() methods check if a string begins or ends with a specified substring, returning True or False.

Example:

filename = "report.pdf"
print(filename.endswith(".pdf"))  # Output: True
print(filename.startswith("rep"))  # Output: True

These methods are useful for validating file extensions or prefixes.

question mark

Which of the following operations are valid for strings in Python?

Select all correct answers

Alt var klart?

Hvordan kan vi forbedre det?

Takk for tilbakemeldingene dine!

Seksjon 2. Kapittel 2

Spør AI

expand

Spør AI

ChatGPT

Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår

Seksjon 2. Kapittel 2
some-alt