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

Python String Operations Overview

The document provides an overview of Python strings, including how to create and access string variables, use negative indexing, and perform slicing. It explains string immutability, multiline strings, string comparison, joining strings, iterating through strings, finding string length, and formatting strings using f-Strings. Sample code snippets are included to illustrate each concept.

Uploaded by

Usharani K
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views6 pages

Python String Operations Overview

The document provides an overview of Python strings, including how to create and access string variables, use negative indexing, and perform slicing. It explains string immutability, multiline strings, string comparison, joining strings, iterating through strings, finding string length, and formatting strings using f-Strings. Sample code snippets are included to illustrate each concept.

Uploaded by

Usharani K
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

PYTHON STRINGS –Sample programs:

1.# create string type variables

name = "Python"
print(name)

message = "I love Python."


print(message)

Access String Characters in Python


greet = 'hello'
print(greet[1]) # "e"
# access 1st index element

[Link] Indexing: Similar to a list, Python allows negative


indexing for its strings.
For example,
greet = 'hello'

# access 4th last element


print(greet[-4]) # "e"
[Link]:
Access a range of characters in a string by using the slicing
operator colon :. For example,
greet = 'Hello'
print(greet[1:4]) # "ell"
# access character from 1st index to 3rd index
[Link] Strings are immutable
message = 'Hola Amigos'
message[0] = 'H'
print(message)
Output

TypeError: 'str' object does not support item assignment

However, we can assign the variable name to a new string. For


example,
message = 'Hola Amigos'
# assign new string to message variable
message = 'Hello Friends'
prints(message); # prints "Hello Friends"
[Link] Multiline String
We can also create a multiline string in Python. For this, we
use triple double quotes """ or triple single quotes '''. For
example,
# multiline string
message = """
Never gonna give you up
Never gonna let you down
"""
print(message)
O/P:

Never gonna give you up


Never gonna let you down
[Link] String Operations
Compare Two Strings
str1 = "Hello, world!"
str2 = "I love Python."
str3 = "Hello, world!"
print(str1 == str2)
print(str1 == str3)
# compare str1 and str2
# compare str1 and str3
O/p
False
True
n the above example,
 str1 and str2 are not equal. Hence, the result is False.
 str1 and str3 are equal. Hence, the result is True.

[Link] Two or More Strings


greet = "Hello, "
name = "Jack"

# using + operator
result = greet + name
print(result)

# Output: Hello, Jack


[Link] Through a Python String
greet = 'Hello'

# iterating through greet string


for letter in greet:
print(letter)
o/p

H
e
l
l
o
[Link] String Length
In Python, we use the len() method to find the length of a
string. For example,
greet = 'Hello'
print(len(greet))
# count length of greet string

# Output: 5
[Link] String Formatting (f-Strings)
Python f-Strings make it really easy to print values and
variables. For example,
name = 'Cathy'
country = 'UK'

print(f'{name} is from {country}')

Common questions

Powered by AI

Python's f-strings offer a clear advantage in string formatting by allowing inline expression evaluation within string literals. This is achieved through embedding expressions directly in the string by prefixing it with an 'f' or 'F', enabling concise and readable formatting. For instance, 'print(f'{name} is from {country}'), where 'name = "Cathy"' and 'country = "UK"', outputs 'Cathy is from UK'. F-strings simplify formatting compared to older methods like '%' or 'str.format()', enhancing both readability and performance .

Multiline strings in Python are defined using triple double quotes '"""' or triple single quotes "'''", allowing the inclusion of multiple lines of text. This is particularly useful for text that spans multiple lines, such as paragraph text in documentation or when producing formatted output. An example definition is 'message = """ Never gonna give you up Never gonna let you down """', which contains line breaks naturally within the string .

Python strings are immutable, meaning once a string is created, it cannot be changed directly. Any attempt to modify a string's content by directly assigning a new value to an index results in a TypeError, as shown by attempting to change 'Hola Amigos' to 'H' at the 0th index. The correct workaround is to create a new string with the desired changes and reassign it to the variable, such as changing 'message = "Hola Amigos"' to 'message = "Hello Friends"' .

Python allows accessing string characters using both positive and negative indexing, providing flexibility in retrieving elements based on their position from either end of the string. Positive indexing starts from 0 from the left, whereas negative indexing begins from -1 from the right. For example, 'greet = "hello"' uses 'greet[1]' to access '"e"' from the left, and 'greet[-4]' for the same character from the right. This dual approach benefits tasks such as reverse lookups or when string length is unknown, thereby facilitating easier string traversal and manipulation in various scenarios .

In Python, strings can be concatenated using the '+' operator, which joins multiple strings into one continuous string. For example, concatenating 'greet = "Hello, "' and 'name = "Jack"' with 'greet + name' results in '"Hello, Jack"'. This method is straightforward and directly appends the second string to the first without additional characters or formatting .

Negative indexing in Python strings allows access to characters from the end of the string by using negative numbers. The index '-1' refers to the last character, '-2' to the second last, and so on. This is particularly useful for quickly retrieving the end parts of a string without needing to know its full length. For instance, in 'greet = "hello"', 'print(greet[-4])' retrieves 'e', which is the second character from the beginning or fourth from the end .

String slicing in Python uses the ':' operator to access a range of characters from a string, specified by start and stop indices. For example, 'greet = "Hello"; print(greet[1:4])' retrieves '"ell"', encompassing characters from index 1 to 3. This method is highly useful for extracting substrings without manually iterating over each character, such as fetching a substring from a file path or parsing specific data elements from formatted strings .

Python allows iteration through each character of a string using a 'for' loop. By iterating over the string, each character can be accessed sequentially, as shown in 'for letter in greet: print(letter)' which prints each character of the string 'greet = "Hello"'. This technique is practical for operations like parsing and analyzing text data, implementing character level transformations, or searching for specific patterns within a string .

Python uses the equality operator '==' to compare strings. It returns 'True' if the strings are identical in sequence and content, and 'False' otherwise. When comparing two identical strings like 'str1 = "Hello, world!"' and 'str3 = "Hello, world!"', the result is 'True'. However, comparing different strings such as 'str1 = "Hello, world!"' and 'str2 = "I love Python."' results in 'False', indicating the strings do not match .

The len() method counts the number of characters in a Python string, including all spaces and special characters. Whitespace is included in the character count, so a string with spaces will yield a higher count compared to one without. For example, given 'greet = "Hello"', 'print(len(greet))' will output 5, counting each letter and the spaces .

You might also like