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

Updated String Functions

Uploaded by

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

Updated String Functions

Uploaded by

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

Strings[immutable]

• Strings are sequence of characters. Python treats single quotes the


same as double quotes.
• Creating strings is as simple as assigning a value to a variable. For
example:
var1 = 'Hello World!'
var2 = "Python Programming"

• To accept string:
name = input(“Enter your name”)
Multiline: (Triple Quotes)

Strings to span multiple lines


• Syntax - three consecutive single or double quotes.
Example:
multiline_string = """This is a
multi-line
string in Python."""
Accessing Values in Strings:
To access substrings, use the square brackets for slicing along with the index or indices to obtain your
substring:
Example:
var1 = 'Hello World!’
var2 = "Python Programming"
print("var1[0]: ", var1[0])
print("var2[1:5]: ", var2[1:5])//slicing
print(var1[-1])
print(var2[:6])
print(var2[7:])
Output:
var1[0]: H
var2[1:5]: ytho
!
Python
Programming
Accessing Values in Strings:
fruit = "apple"
for x in fruit:
print(x)
Output:
a
p
p
l
e
Concatenation (+operator)
Joining of two or more strings.

first_name ="Virat"
last_name = "Kohli"
name = first_name + last_name
print(name)
name = first_name +" " + last_name
print(name)

Output:
ViratKohli
Virat Kohli
Concatenation (*operator)-
appending the same string to the string

Example Output
first_name ="Dhoni" DhoniDhoniDhoni
name = first_name * 3
print(name)
f_name = "MS" MSDhoniDhoniDhoni
l_name = "Dhoni" MSDhoniMSDhoniMSDhoni
name1 = f_name + l_name * 3
name2 = (f_name + l_name) *3
print(name1)
print(name2)
len()
returns the number of characters

lang = "python programming"


l = len(lang)
print(l)

Output: 18
lower() and upper()
Converts all the alphabets in the string to lowercase/uppercase.

original_string = "Hello, World!"


lower_case_string = original_string.lower()
print(lower_case_string)

Output: hello, world!

original_string = "Hello, World!"


upper_case_string = original_string.upper()
print(upper_case_string)

Output: "HELLO, WORLD!"


Concatenating Strings
Output:
Strings can be joined using str.join() method. Hello World
Example: Hello World
Hello,World
str1 = "Hello" + " " + "World" #using + H,e,l,l,o, ,W,o,r,l,d
str2 = " ".join(["Hello", "World"]) #using join H,e,l,l,o
str3 = ",".join(["Hello", "World"]) #using join

str4=",".join("Hello World")
str5=",".join("Hello")
print(str1)
print(str2)
print(str3)
print(str4)
print(str5)
Critical Thinking

Why might join() be preferred


over using the + operator for
concatenating a large number
of strings in Python? Discuss
how the choice of method
impacts memory usage and
execution speed.
endswith() and startswith()

These methods check if a string ends or starts with a specified substring.


Example:
print("Hello".endswith("o"))
print("Hello".startswith("H"))
output:
True
True
Critical Thinking

How could the startswith()


and endswith() methods be used to
enhance security checks in file
processing applications? Provide
examples of how incorrect use of
these methods could lead to
security vulnerabilities.
string[start:end:step]

It is used for slicing strings. This slicing mechanism allows you to extract a substring from a string, with the
ability to specify the starting index, the ending index, and the step.
• start: This is the index at which the slice starts. If it is omitted or specified as None, slicing starts at the
beginning of the string. For example, string[:end] will slice from the beginning of the string up to, but not
including, the index end.
• end: This is the index at which the slice ends. The character at this index is not included in the resulting
substring. If omitted or None, slicing goes up to and including the end of the string. For example,
string[start:] will slice from start to the end of the string.
• step: This specifies the substring between elements in the slice. It determines how many indices are
skipped within the range of [start, end). The default value is 1, which means it includes every character in
the specified range. A different step lets you include characters at regular intervals. For example,
string[start:end:2] will include characters starting from start up to, but not including, end, with every
second character selected.
Example:
text = "Hello, World!"
# Extract "Hello"
print(text[0:5]) # Outputs: Hello
# Extract "World"
print(text[7:12]) # Outputs: World
# Extract every second character in "Hello, World!"
print(text[::2]) # Outputs: Hlo ol!
# Extract the string in reverse
print(text[::-1]) # Outputs: !dlroW ,olleH
# Omitting start and end, using step
print(text[::3]) # Outputs: Hl r!
Find the output:
paragraph = "python is POWERFUL and FAST, plays well with others, runs everywhere, is FRIENDLY & EASY to
learn”
formatted_paragraph=paragraph+"."

formatted_paragraph = formatted_paragraph[0].upper() + formatted_paragraph[1:].lower()


if not formatted_paragraph.endswith('.'):
formatted_paragraph += '.'

print(formatted_paragraph)
Developers[PLA<2] Achiever[PLA<4] Innovators [PLA >= 4]

Accept a string. If the string is of even Accept a string and display a Accept two strings, a and b and display the
length, output the first half. new string made of 3 copies of the result of putting them together in the order
last 2 chars of the original abba,
Example: string. The string length will be at
Enter the string: WooHoo least 2. Example:
Output: Woo Enter the string:Hi
Enter the string: WoooHoo Example: Enter the string:Bye
Output: Not of even length Enter the string: Hello Output:HiByeByeHi
Output:
lololo
Accept 2 strings. Output their Accept a string and display a new Write a function middle() to accept a string

Any concatenation, except omit the first char of


each. The strings will be at least length 1.
string made of 3 copies of the last
2 chars of the original string. The
and return a new string without the first and
last char. The string length will be at least 2.
Example:
Example: string length will be at least 2.
One Enter first string: Computer
Enter second string: Science
Example:
Enter the string: Hello
middle("Hello”) returns "ell"

Output: omputercience Output:


lololo
Accept two strings, a and b and display the Write a function middle() to accept Write a function rotated() to accept a string and
result of putting them together in the order a string and return a new string an integer. Return a "rotated left 2" where the
abba, without the first and last char. The first 2 chars are moved to the end. The string
Example: string length will be at least 2. length will be at least 2.
Enter the string:Hi Example: Example:
Enter the middle("Hello”) returns "ell" rotated("Hello”,2) returns "lloHe".
string:Bye Output:HiByeBy rotated(“computer”,4) returns “utercomp”
eHi

Ask the user to enter a filename and then Accept a list of URLs and prints out Accept a list of filenames. Separate them into
check if the file has an appropriate image whether each URL starts with different lists based on their extensions. The
file extension (e.g., .jpg, .png, .gif). The "http" or "https". For each URL, the program should categorize files into 'Photos',
program should print a message indicating program should output an 'Videos', and 'Documents', and display them with
whether the file is an image file or not. appropriate message. appropriate messages. Assume 'Photos' end with
.jpg or .png, 'Videos' end with .mp4 or .avi, and
Extended task:
Write a program to -

a) accept a word and check if it is a palindrome or not.

b) accept a sentence and find the longest word in the String


Finding a Substring Replacing Substrings
• find() returns the lowest index of the substring if found, replace() substitutes occurrences of a specified substring
else -1. with another.
Example: Example:
print("Hello world".find("world")) print("Hello world".replace("world", "Python"))
output: Output:
6 Hello Python
• find(a,b) returns the index within the range

Example:
text="Hello, world! This is an example. Hello world?."
index = text.find("Hello", 10)
print(index)
index = text.find("world", 10, 20)
print(index)
Output:
34
-1
Checking String Properties Counting Substring Occurrences
Methods isalpha(), isdigit(), isalnum(), and islower() count() returns the number of occurrences of a substring.
check for alphabetic, digit-only, alphanumeric Example:
characters, and lowercase strings respectively.
print("Hello world".count("o"))
Example:
print("Mississippi".count("iss"))
print("abc".isalpha())
Output:
print("123".isdigit())
2
print("abc123".isalnum())
2
print("hello".islower())
Output:
True
True
True
True
Joining Iterable into String
join() combines an iterable of strings into a single string, separated by the string called
upon.
Example:
str=", ".join(["apple", "banana", "cherry"])
str1="".join(["apple", "banana", "cherry"])
print(str)
print(str1)
Output:
apple, banana, cherry
applebananacherry
Escape Sequences
Escape sequences allow for inserting special characters in strings, like newlines (\n) or tabs (\t).
Example:
print("First line.\nSecond line.")
print("First line.\tSecond line")
Output:
First line.
Second line.
First line. Second line

You might also like