0% found this document useful (0 votes)
16 views10 pages

Python String Basics and Operations

The document provides a comprehensive overview of strings in Python, detailing their definition, creation, indexing, slicing, and various operations such as concatenation and membership checking. It also covers string comparison, traversal methods, and built-in string handling functions for case conversion, property checking, counting substrings, and splitting/joining strings. Overall, it serves as a guide for understanding and manipulating strings effectively in Python programming.

Uploaded by

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

Python String Basics and Operations

The document provides a comprehensive overview of strings in Python, detailing their definition, creation, indexing, slicing, and various operations such as concatenation and membership checking. It also covers string comparison, traversal methods, and built-in string handling functions for case conversion, property checking, counting substrings, and splitting/joining strings. Overall, it serves as a guide for understanding and manipulating strings effectively in Python programming.

Uploaded by

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

Strings in Python

Definition:
In Python, a string is an immutable sequence of Unicode characters. Each character has a
unique numeric value as per the UNICODE standard.
But, the sequence as a whole, doesn't have any numeric value even if all the characters are
digits.
To differentiate the string from numbers and other identifiers, the sequence of characters is
included within single, double or triple quotes in its literal representation. Hence, 1234 is a
number (integer) but '1234' is a string.
Creating Python Strings
As long as the same sequence of characters is enclosed, single or double or triple quotes don't
matter. Hence, following string representations are equivalent.
Example
>>> 'Welcome To TutorialsPoint'
'Welcome To TutorialsPoint'
>>> "Welcome To TutorialsPoint"
'Welcome To TutorialsPoint'
>>> '''Welcome To TutorialsPoint'''
'Welcome To TutorialsPoint'
>>> """Welcome To TutorialsPoint"""
'Welcome To TutorialsPoint'
Note: Looking at the above statements, it is clear that, internally Python stores strings
as included in single quotes.

Accessing Values in Strings


String Indexing:
In Python, a string is an ordered sequence of Unicode characters. Each character in the string
has a unique index in the sequence.
The index starts with 0. First character in the string has its positional index 0. The index
keeps incrementing towards the end of string.
If a string variable is declared as var="HELLO PYTHON", index of each character in the
string is.

[Link] Babu([Link] Computer Science)


Python allows you to access any individual character from the string by its index.
In this case, 0 is the lower bound and 11 is the upper bound of the string.
Note: So, var[0] returns H, var[6] returns P. If the index in square brackets exceeds the upper
bound, Python raises IndexError.
Example
var = "HELLO PYTHON"
>>>print(var[0]) #’H’
>>>print(var[7]) #’Y’
>>>print(var[11]) #’N’
>>>print(var[12]) #Index Error

String Negative & Positive Indexing:


One of the unique features of Python sequence types (and therefore a string object) is that it
has a negative indexing scheme also.
In the example above, a positive indexing scheme is used where the index increments from
left to right.
In case of negative indexing, the character at the end has -1 index and the index decrements
from right to left, as a result the first character H has -12 index.

[Link] Babu([Link] Computer Science)


Example:
var = "HELLO PYTHON"
print(var[-1]) #’N’
print(var[-5]) #’Y’
print(var[-12]) #’H’
print(var[-13]) #Index Error

Slicing Strings
Python String slicing is a way of creating a sub-string from a given string. In this process, we
extract a portion or piece of a string. Usually, we use the slice operator "[ : ]" to perform
slicing on a Python String.
Syntax:
String_name[start : stop : step-size]

start(optional) : starting index number(optional) default start with index number 0


(Implicity).
stop(optional) : Ending index number(optional) default last index number (Explicity).
Step_size(optional): [Link] index numbers increments default increments 1

String Operations
1. Repeating Strings: The simplest way to repeat a string is by using the multiplication
operator (*), which repeats the string a specified number of times.

Example:
string = "hello"
repeated_string = string * 3
print(repeated_string)

2. Concatenation of Strings: String concatenation in Python refers to combining


multiple strings into one. we can use the + operator to concatenate strings directly.

Example:
string1 = "Hello"
string2 = "World"
result = string1 + " " + string2
print(result)

[Link] Babu([Link] Computer Science)


3. Checking Membership:
In Python, the membership operator is used to test if a value or variable is found in a
sequence (like a string, list, tuple, etc.). For strings, the membership operators are in
and not in.

1. Using in Operator:

The in operator checks if a substring exists within a string. It returns True if the
substring is found, and False otherwise.

Example:

string = "Hello, World!"


substring = "World"

# Check if substring is in string


if substring in string:
print("Found!")

else:
print("Not found!")

2. Using not in Operator:

The not in operator checks if a substring does not exist within a string. It returns
True if the substring is not found, and False otherwise.

Example:
string = "Hello, World!"
substring = "Python"

# Check if substring is not in string


if substring not in string:
print("Not found!")

else:
print("Found!")

4. Comparing Strings:

In Python, you can compare strings using various operators to check for equality,
inequality, lexicographical order, and more. Here are the main ways to compare
strings in Python:

[Link] Babu([Link] Computer Science)


1. Using == (Equality Operator):

The == operator checks if two strings are exactly equal, i.e., they have the same
characters in the same order.

Example:

string1 = "hello"
string2 = "hello"
string3 = "world"

print(string1 == string2) # True (both are "hello")


print(string1 == string3) # False (different strings)

2. Using != (Inequality Operator):


The != operator checks if two strings are not equal, i.e., they differ in at least one
character.
Example:
string1 = "apple"
string2 = "orange"
string3 = "apple"

print(string1 != string2) # True (different strings)


print(string1 != string3) # False (same strings)

3. Using > and < (Lexicographical Comparison):

Strings in Python can be compared lexicographically (dictionary order). The >


operator checks if the first string is lexicographically greater than the second, and <
checks if it is smaller.

Example:

string1 = "apple"
string2 = "banana"
string3 = "apple"

print(string1 < string2) # True (because "apple" comes before "banana")


print(string1 > string2) # False
print(string1 == string3) # True (same strings)

[Link] Babu([Link] Computer Science)


Traversing of String
1. Traversing a string in Python refers to the process of accessing each character within
the string, one by one. Python offers several ways to achieve this:

Using a for loop (direct iteration):

This is the most common and Pythonic way to traverse a string. The for loop directly
iterates over the characters of the string.

Example:

my_string = "Python"

#Access list of characters using for loop


for char in my_string:
print(char)

Using a for loop with range() and len() (by index):

This method uses the index of each character to access it. You get the length of the
string using len() and then iterate through the range of indices.

Example:

my_string = "Python"
n=len(my_string)

#Access list of characters using range()


for i in range(n):
print(my_string[i])

Using a while loop (by index):

Similar to the for loop with range(), you can use a while loop to iterate through the
indices of the string.

Example:

my_string = "Python"
index = 0
n=len(my_string)

#access list characters using while loop


while (index < n):
print(my_string[index])
index += 1

[Link] Babu([Link] Computer Science)


String Handling Functions
Python offers a rich set of built-in functions and string methods for handling and
manipulating strings.
These functionalities enable various operations, from case conversion to searching
and formatting.

Common String Handling Functions and Methods:

1. Case Conversion:

upper(): Converts all characters in a string to uppercase.


lower(): Converts all characters in a string to lowercase.
capitalize(): Converts the first character of a string to uppercase and the rest to
lowercase.
title(): Converts the first character of each word to uppercase and the rest to
lowercase.
swapcase(): Swaps the case of all characters (uppercase to lowercase, and vice versa).

Ex 1: Write a program change string test cases

name="Hello Python"

name=[Link]()
print("After convert uppercase:",name)

name=[Link]()
print("After convert lowercase:",name)

name=[Link]()
print("After convert Capitalize:",name)

name=[Link]()
print("After convert title:",name)

name=[Link]()
print("After convert swapcase:",name)

output:
After convert uppercase: HELLO PYTHON
After convert lowercase: hello python
After convert Capitalize: Hello python
After convert title: Hello Python
After convert swapcase: hELLO pYTHON

[Link] Babu([Link] Computer Science)


2. Checking String Properties (Boolean Methods):

isalnum(): Returns True if all characters are alphanumeric.


isalpha(): Returns True if all characters are alphabetic.
isdigit(): Returns True if all characters are digits.
islower(): Returns True if all cased characters are lowercase.
isupper(): Returns True if all cased characters are uppercase.
isspace(): Returns True if all characters are whitespace.
istitle(): Returns True if the string is title-cased.

#Write Program check test case strings

name=input(“Enter a String:”)

print([Link]())
print([Link]())
print([Link]())
print([Link]())
print([Link]())
print([Link]())
print([Link]())

3. Counting substring in a String:


To count the occurrences of a substring in a string in Python, you can use the
count() method of the string object. Here's an example:

Example:
text = "hello world, hello universe"
substring = "hello"
# Counting occurrences of 'hello'
count = [Link](substring)
print(count)
4. Replacing a string with another string:
In Python, you can replace a substring with another string using the replace()
method. Here's a simple example:

Example:
text = "hello world, hello universe"
old_substring = "hello"
new_substring = "hi"
# Replacing 'hello' with 'hi'
new_text = [Link](old_substring, new_substring)
print(new_text)

[Link] Babu([Link] Computer Science)


5. Splitting and joining string:

In Python, you can split and join strings using the split() and join() methods,
respectively.

1. Splitting a String

The split() method is used to break a string into a list of substrings based on a
delimiter.

Example:
text = "apple,banana,orange"
# Splitting string by commas
words = [Link](',')
print(words)

Output:
['apple', 'banana', 'orange']

By default, split() divides the string at whitespace characters, but you can specify
any delimiter, like a comma, space, etc.

You can also limit the number of splits by passing a second argument:

Example:

text = "apple,banana,orange"
# Splitting string by commas, but limiting to 2 splits
words = [Link](',', 2)
print(words)

Output:
['apple', 'banana', 'orange']

2. Joining a List of Strings


The join() method is used to join elements of a list (or any iterable) into a single
string, using a specified delimiter.

Example:
words = ['apple', 'banana', 'orange']
# Joining list with commas
text = ','.join(words)
print(text)

Output:
apple,banana,orange

[Link] Babu([Link] Computer Science)


join() is used with a delimiter (in this case, a comma) to join all elements of the
list into a single string.
You can also join with spaces or other characters:

Ex 1:
text = ' '.join(words)
print(text)

Output:
apple banana orange

[Link] Babu([Link] Computer Science)

You might also like