0% found this document useful (0 votes)
10 views6 pages

Strings in Python

The document provides an overview of Python strings, including their creation, accessing characters, string slicing, and immutability. It explains various string methods, such as len(), upper(), lower(), strip(), and replace(), as well as how to concatenate and format strings. Additionally, it covers string membership testing using the 'in' keyword.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
10 views6 pages

Strings in Python

The document provides an overview of Python strings, including their creation, accessing characters, string slicing, and immutability. It explains various string methods, such as len(), upper(), lower(), strip(), and replace(), as well as how to concatenate and format strings. Additionally, it covers string membership testing using the 'in' keyword.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 6

Python String

A string is a sequence of characters. Python treats anything inside quotes as a string. This
includes letters, numbers, and symbols. Python has no character data type so single
character is a string of length 1.

Creating a String-

Strings can be created using either single (‘) or double (“) quotes.

# program to generate a string

s1 = ‘ABC'

s2 = “XYZ"

print(s1)

print(s2)

Multi-line Strings-

If we need a string to span multiple lines then we can use triple quotes (”’ or “””).

# Sample program for multi line string

s = """I am in second year

at Hindustan"""

print(s)

# output

# I am in second

# year at Hindustan

Accessing characters in Python String

Strings in Python are sequences of characters, so we can access individual characters


using indexing. Strings are indexed starting from 0 and 1 from end. This allows us to retrieve
specific characters from the string.

Ex: Accessing characters

s = “LITERATURE"

print(s[0]) #ouput=L
print(s[4]) #output=R

Note: Accessing an index out of range will cause an IndexError. Only integers are allowed as
indices and using a float or other types will result in a TypeError.

Access string with Negative Indexing

Python allows negative address references to access characters from back of the String,

e.g. -1 refers to the last character, -2 refers to the second last character, and so on.

# sample program

s = “LITERATURE"

print(s[-10])

print(s[-5])

String Slicing

Slicing is a way to extract portion of a string by specifying the start and end indexes.

The syntax for slicing is string[start:end], where start starting index and end is stopping
index (excluded).

s = “ALLTHEBEST"

# Retrieves characters from index 1 to 3: ‘LLT'

print(s[1:4])

# Retrieves characters from beginning to index 2: ‘ALL'

print(s[:3])

# Retrieves characters from index 3 to the end: ‘THEBEST'

print(s[3:])

# Reverse a string

print(s[::-1])

#output is ‘TSEBEHTLLA’
String Immutability

Strings in Python are immutable. This means that they cannot be changed after they are
created. If we need to manipulate strings then we can use methods like concatenation,
slicing, or formatting to create new strings based on the original.

# to change the first character in the string

s = “LOVEINDIA"

# s[0] = 'I' # Uncommenting this line will cause a TypeError

# Instead, create a new string

s = “I" + s[0:]

print(s)

#output is ‘ILOVEINDIA’

Deleting a String

In Python, it is not possible to delete individual characters from a string since strings are
immutable. However, we can delete an entire string variable using the del keyword.

# example

s = "GfG"

del s # Deletes entire string

Note: After deleting the string using del and if we try to access s then it will result in
a NameError because the variable no longer exists.

Updating a String

To update a part of a string we need to create a new string since strings are immutable.

# example

s = "hello Alice“

# Update- “h” by “H”

S1 = "H" + s[1:]

print(s1)
# replace “Alice" with “Varun"

S2= s1.replace(“Alice", “Varun")

print(s2)

Common String Methods- Python provides a various built-in methods to manipulate strings.
len(): The len() function returns the total number of characters in a string.

s = “Computer"

print(len(s))

# output: 8

Common String Methods

upper() and lower():

upper() method converts all characters to uppercase.

lower() method converts all characters to lowercase.

s = "Hello World"

print(s.upper()) # output: HELLO WORLD

print(s.lower()) # output: hello world

strip() and replace():

strip() removes leading and trailing whitespace from the string

replace(old, new) replaces all occurrences of a specified substring with another.

# Remove spaces from both ends

s = " ABC "

print(s.strip())

# Replaces 'fun' with 'awesome'

s = "Python is fun"

print(s.replace("fun", "awesome"))

Concatenating and Repeating Strings

We can concatenate strings using + operator and repeat them using * operator.
Strings can be combined by using + operator.

s1 = "Hello"

s2 = "World"

s3 = s1 + " " + s2

print(s3)

# output is ‘Hello World’

We can repeat a string multiple times using * operator.

s = "Hello "

print(s * 3)

# output ‘Hello Hello Hello ‘

Formatting Strings

Python provides several ways to include variables inside strings.

Using f-strings

The simplest and most preferred way to format strings is by using f-strings.

name = "Alice"

age = 22

print(f"Name:”, {name}, “Age: “, {age})

#output is ‘Name: Alice, Age: 22’

Using format()

Another way to format strings is by using format() method.

# example program

s = "My name is {} and I am {} years old.“

s1= s.format("Alice", 22)

print(s1)
Using in for String Membership Testing

The in keyword checks if a particular substring is present in a string.

s = “ANECDOTE"

print(“DOT" in s) #output True

print(“XYZ" in s) #output False

You might also like