Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
16 views

01string in Pythonpdf

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

01string in Pythonpdf

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

Javed oad

BS COMPUTER SCIENCE
quest university
javedoad85@gmail.com

• CWO ACADMEY Code with Oad Acadmey

Title: String in python


Subtitle:
Javed Oad (BS computer science)
Date 14/10/2024
Definition

In Python, a string is a sequence of


characters enclosed
within single quotes
(' '), double quotes (" "), or triple quotes (''' ''' or
""" """).
Strings are used to represent text and can
include letters,
numbers, symbols, and whitespace.
Simple string
Three different way Explenataion
• str1="hello world" • " javed's cup"
• str2='hello world' • ' javed"s cup'
• str3="""hello world"""
• repeated = 'Ha' * 3 #
Output: 'HaHaHa‘

• a='javed'
• b='oad'
• print(a+b*2) #javedoadoad
Example
• # Example of built-in
functions

• print("Hello, World!")
• result = len([1, 2, 3])
Concatenation
In Python, • first_name = "John"
concatenation refers • last_name = "Doe"
to the operation • full_name = first_name
of joining two or more + " " + last_name
strings • print(full_name)
together into one
continuous string. This
is done using
the + operator.
Concatenation
Important Points: • age = 30
•Only strings can be • message = "I am " +
concatenated: If you try str(age) + " years
to concatenate a string old."
•with a number (int or
float), Python will
• raise a TypeError. You
must convert the number to
a string first using str().
Concatenation

Concatenation does not add spaces: If you


want spaces between concatenated strings, you
must include them explicitly.
Concatenation
• str1="hello" • "hello"+"world" ------
• str2="world" >"hello world“
• print(str1+str2)#helloworld
• length os str
• print(str) • len(str)
• len1=len(str1)
• print(len1)
Indexing
• Indexing in Python • text = "Python“
refers to accessing •text[0] gives 'P' (the
individual elements of a first character)
sequence (such as a •text[1] gives 'y' (the
second character)
string, list, or tuple) •text[2] gives 't' (the
using their position third character)
within that sequence. •text[-1] gives 'n' (the
Each element in the last character)
•text[-2] gives 'o' (the
sequence has a specific second to last
index, starting from 0 character)
for the first element.
Key Points:
•Zero-based Indexing: The first element is accessed with an
index of 0.
•Negative Indexing: You can also use negative numbers
• to index from the end of the sequence. For example, text[-1]
refers to the last element.
•IndexError: If you try to access an index that is out of
range,
• Python will raise an IndexError.
Indexing
• Str=“hello world”

• Str[0] is h
• Str[1] is e

• Str[0] =“mj” is not allow


Slicing

Slicing in Python is a technique used to extract a


specific portion or subset of elements from a
sequence (like a string, list, or tuple) by specifying
a range of indices. The syntax for slicing is:

sequence[start:stop:step]
Example with a String:
text = "Python"

•text[0:4] gives "Pyth" (from index 0 to 3, as stop is exclusive)


•text[2:] gives "thon" (from index 2 to the end)
•text[:3] gives "Pyt" (from the beginning to index 2)
•text[::2] gives "Pto" (every second character from the start)
•text[::-1] gives "nohtyP" (reverses the string)
Slicing
• Definition: • Negative
Str[staring_index:ending_ind] • Str=“helloworld”
• Str=“helloworld” • Str=[-3:-1]
• Str[1:4] is “eo”
• Str[ :0] is same [0:4]
• 4Str[1 :0] is same
str[1:len(0tr)]
string function
• In Python, string functions are built-in
methods that allow you to perform various
operations on strings, such as manipulating
text, searching within a string, formatting, and
more. These functions are called on string
objects and return a new string or a specific
value, depending on the operation.
len(): Returns the length of the string.
text = "Hello"
length = len(text) # Output: 5
str(): Converts an object to a string .

num = 100
string_num = str(num) # Output: "100"
lower(): Converts all characters in the string to lowercase.
text = "Hello"
print(text.lower()) # Output: "hello"
upper(): Converts all characters in the string to uppercase.
text = "Hello"
print(text.upper()) # Output: "HELLO"
replace(old, new): Replaces occurrences of a substring within the string with a new substring
text = "Hello World"
print(text.replace("World", "Python")) #
Output: "Hello Python"
find(substring): Returns the index of the first occurrence of a substring within the string. Returns -1 if the substring is not found.

text = "Hello"
index = text.find("e") # Output: 1
split(separator): Splits the string into a list of substrings based on a separator.
text = "apple,banana,cherry"
fruits = text.split(",") # Output: ['apple',
'banana', 'cherry']
join(iterable): Joins elements of an iterable (e.g., list) into a single string, with a specified separator.
fruits = ['apple', 'banana', 'cherry']
result = ", ".join(fruits) # Output: "apple,
banana, cherry"
text = " Hello "
print(text.strip()) # Output: "Hello"
startswith(prefix): Returns True if the string starts with the specified prefix, otherwise False.
text = "Hello"
result = text.startswith("He") # Output: True
endswith(suffix): Returns True if the string ends with the specified suffix, otherwise False .

text = "Hello"
result = text.endswith("lo") # Output: True
text = "Python Programming"

# Converting to uppercase
print(text.upper()) # Output: "PYTHON PROGRAMMING"

# Replacing a substring
print(text.replace("Python", "Java")) # Output: "Java Programming"

# Finding a substring
print(text.find("Pro")) # Output: 7

# Splitting the string


words = text.split(" ") # Output: ['Python', 'Programming']

# Joining a list into a string


sentence = " ".join(words) # Output: "Python Programming"

You might also like