0% found this document useful (0 votes)
4 views33 pages

3-String Sequence in Python

The document provides an overview of string handling in Python, covering string declaration, indexing, operators, and various built-in functions and methods. It includes examples of how these concepts can be applied in robotic manufacturing and chatbots for tasks such as data logging, user input processing, and error handling. Key functions discussed include concatenation, repetition, membership checks, and string manipulation methods like replace, find, and split.

Uploaded by

Harsha Harsha
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)
4 views33 pages

3-String Sequence in Python

The document provides an overview of string handling in Python, covering string declaration, indexing, operators, and various built-in functions and methods. It includes examples of how these concepts can be applied in robotic manufacturing and chatbots for tasks such as data logging, user input processing, and error handling. Key functions discussed include concatenation, repetition, membership checks, and string manipulation methods like replace, find, and split.

Uploaded by

Harsha Harsha
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

String Declaration
Strings in Python
• In python, strings can be created by enclosing the character or
the sequence of characters in the quotes.
• Python allows us to use single quotes, double quotes, or triple
quotes to create strings.
Example:
str1 = 'Hello Python'
str2 = "Hello Python"
str3 = '''Hello Python'''

• In python, strings are treated as the sequence of characters


which means that python doesn't support the character data
type instead a single character written as 'p' is treated as the
string of length 1.
String Indexing
String Indexing in Python
• Like other programming languages, the indexing of the python
strings starts from 0. For example, the string "HELLO" is indexed as
given in the below figure.
str="HELLO"

str[0]=H
str[1]=E
str[4]=O
• Python allows negative indexing for its sequences.
• The index of -1 refers to the last item, -2 to the second last item and
so on.
str[-1]=O
str[-2]=L
str[-4]=E
String Operators
String Operators in Python
+ It is known as concatenation operator used to join the strings.
* It is known as repetition operator. It concatenates the multiple copies
of the same string.
[] It is known as slice operator. It is used to access the sub-strings of a
particular string.
[:] It is known as range slice operator. It is used to access the characters
from the specified range.
in It is known as membership operator. It returns if a particular
sub-string is present in the specified string.

not in It is also a membership operator and does the exact reverse of in. It
returns true if a particular substring is not present in the specified
string.
r/R It is used to specify the raw string. To define any string as a raw string,
the character r or R is followed by the string. Such as "hello \n
python".
% It is used to perform string formatting. It makes use of the format
specifies used in C programming like %d or %f to map their values in
python.
String Operators in Python cont…
Example: “[Link]”
str1 = "Hello"
str2 = " World"
print(str1*3) # prints HelloHelloHello
print(str1+str2) # prints Hello world
print(str1[4]) # prints o
print(str1[2:4]) # prints ll
print('w' in str1) # prints false as w is not present in str1
print('Wo' not in str2) # prints false as Wo is present in str2.
print(r'Hello\n world') # prints Hello\n world as it is written
print("The string str1 : %s"%(str1)) # prints The string str : Hello

Output: python [Link]


HelloHelloHello
Hello World
o
ll
False
False
Hello\n world
The string str1 : Hello
String Functions & Methods
String Functions & Methods in Python
• Python provides various in-built functions & methods that are
used for string handling. Those are
• len() • find()
• lower() •index()
• upper() • isalnum()
• replace() • isdigit()
• join() • isnumeric()
• split() • islower()
☞ len(): • isupper()
• In python, len() function returns length of the given string.
Syntax: len(string)
Example: [Link] Output:
str1="Python Language" python [Link]
print(len(str1)) 15
String Functions & Methods in Python
Cont..
☞ lower ():
• In python, lower() method returns all characters of given string in
lowercase.
Syntax:
[Link]()
Example: [Link] Output:
str1="PyTHOn" python [Link]
print([Link]()) python
☞ upper ():
• In python, upper() method returns all characters of given string in uppercase.
Syntax:
[Link]()

Example: [Link] Output:


str="PyTHOn" python [Link]
print([Link]()) PYTHON
String Functions & Methods in Python
Cont..
☞ replace()
• In python, replace() method replaces the old sequence of
characters with the new sequence.
Syntax: [Link](old, new[, count])
Example: [Link]
str = "Java is Object-Oriented Java"
str2 = [Link]("Java","Python")
print("Old String: \n",str)
print("New String: \n",str2)
str3 = [Link]("Java","Python",1)
print("\n Old String: \n",str)
print("New String: \n",str3)
Output: python [Link]
Old String: Java is Object-Oriented and Java
New String: Python is Object-Oriented and Python
Old String: Java is Object-Oriented and Java
New String: Python is Object-Oriented and Java
String Functions & Methods in Python
Cont..
☞ split():
• In python, split() method splits the string into a comma separated list.
The string splits according to the space if the delimiter is not provided.
Syntax: [Link]([sep="delimiter"])
Example: [Link]
str1 = "Python is a programming language"
str2 = [Link]()
print(str1);print(str2)
str1 = "Python,is,a,programming,language"
str2 = [Link](sep=',')
print(str1);print(str2)

Output: python [Link]


Java is a programming language
['Java', 'is', 'a', 'programming', 'language']
Java, is, a, programming, language
['Java', 'is', 'a', 'programming', 'language']
String Functions & Methods in Python
Cont..
☞ find():
• In python, find() method finds substring in the given string and returns
index of the first match. It returns -1 if substring does not match.
Syntax: [Link](sub[, start[,end]])
Example: [Link]
str1 = "python is a programming language"
str2 = [Link]("is")
str3 = [Link]("java")
str4 = [Link]("p",5)
str5 = [Link]("i",5,25)
print(str2,str3,str4,str5)

Output:
python [Link]
7 -1 12 7
String Functions & Methods in Python
Cont..
☞ index():
• In python, index() method is same as the find() method except it returns
error on failure. This method returns index of first occurred substring
and an error if there is no match found.
Syntax: str. index(sub[, start[,end]])
Example: [Link]
str1 = "python is a programming language"
str2 = [Link]("is")
print(str2)
str3 = [Link]("p",5)
print(str3)
str4 = [Link]("i",5,25) Output:
print(str4) python [Link]
str5 = [Link]("java") 7
print(str5) 12
7
Substring not found
String Functions & Methods in Python
Cont..
☞ isalnum():
• In python, isalnum() method checks whether the all characters of the
string is alphanumeric or not.
• A character which is either a letter or a number is known as
alphanumeric. It does not allow special chars even spaces.
Syntax: [Link]()
Example: [Link]
str1 = "python"
str2 = "python123" Output:
str3 = "12345" python [Link]
str4 = "python@123" True
str5 = "python 123" True
print(str1. isalnum()) True
print(str2. isalnum()) False
print(str3. isalnum()) False
print(str4. isalnum())
print(str5. isalnum())
String Functions & Methods in Python
Cont..
☞ isdigit():
• In python, isdigit() method returns True if all the characters in the string
are digits. It returns False if no character is digit in the string.
Syntax: [Link]()
Example: [Link]
str1 = "12345"
str2 = "python123"
str3 = "123-45-78"
str4 = "IIIV" Output:
str5 = "/u00B23" # 23 python [Link]
str6 = "/u00BD" # 1/2 True
print([Link]()) False
print([Link]()) False
print([Link]()) False
print([Link]()) True
print([Link]()) False
print([Link]())
String Functions & Methods in Python
Cont..
☞ isnumeric():
• In python, isnumeric() method checks whether all the characters of the
string are numeric characters or not. It returns True if all the characters
are numeric, otherwise returns False.
Syntax: str. isnumeric()
Example: [Link]
str1 = "12345"
str2 = "python123"
str3 = "123-45-78" Output:
str4 = "IIIV" python [Link]
str5 = "/u00B23" # 23 True
str6 = "/u00BD" # 1/2
False
print([Link]())
print([Link]())
False
print([Link]()) False
print([Link]()) True
print([Link]()) True
print([Link]())
String Functions & Methods in Python
Cont..
☞ islower():
• In python, islower() method returns True if all characters in the string
are in lowercase. It returns False if not in lowercase.
Syntax: [Link]()
Example: [Link]
str1 = "python"
str2="PytHOn"
str3="python3.7.3"
print([Link]())
print([Link]())
Output:
print([Link]())
python [Link]
True
False
True
String Functions & Methods in Python
Cont..
☞ isupper():
• In python string isupper() method returns True if all characters in the
string are in uppercase. It returns False if not in uppercase.
Syntax: [Link]()
Example: [Link]
str1 = "PYTHON"
str2="PytHOn"
str3="PYTHON 3.7.3"
print([Link]())
print([Link]())
Output:
print([Link]())
python [Link]
True
False
True
For robotic manufacturing and chatbots, string operators and functions are crucial for handling text data. Here's a breakdown of
how each can be applied in these scenarios.

String Operators

+ (Concatenation)

Robotic Manufacturing:

● Scenario: Combining sensor readings or status messages to generate logs.


● Example: log_message = "Part ID: " + part_id + ", Status: " + status

Chatbots:

● Scenario: Building dynamic responses by combining user input with pre-written phrases.
● Example: user_name = "Alice" response = "Hello, " + user_name + ". How can I help you
today?"

* (Repetition)

Robotic Manufacturing:

● Scenario: Creating visual alerts or separators in a console log.


● Example: separator = "*" * 20 print(separator + " END OF CYCLE " + separator)

Chatbots:

● Scenario: Generating simple, repetitive visual elements for formatting, such as a line of hyphens to separate topics.
● Example: print("-" * 30)
in and not in (Membership)
Robotic Manufacturing:
● Scenario: Checking if a specific error code or a part number is present
in a status report.
● Example: error_log = "Error 404: Sensor failure on line
2" if "Error 404" in error_log: print("Critical error
detected.")
Chatbots:
● Scenario: Detecting keywords in a user's message to determine their
intent.
● Example: user_query = "What is the status of my order?"
if "status" in user_query:
respond_with_order_status()
String Functions & Methods
.upper() and .lower()
Robotic Manufacturing:
● Scenario: Standardizing input from various sources (e.g., manual
entries or scanners) for consistent processing.
● Example: part_id = "aBc123".upper() # part_id is now
"ABC123"
Chatbots:
● Scenario: Making a chatbot's responses case-insensitive by
converting user input to a standard case before processing.
● Example: user_input = "Hi" if user_input.lower() ==
"hi": print("Hello! I can help you.")
.strip()

Robotic Manufacturing:

● Scenario: Cleaning up data from a file or sensor to remove unwanted leading


or trailing spaces.
● Example: raw_data = " 123.45 " clean_data =
float(raw_data.strip()) # clean_data is now 123.45

Chatbots:

● Scenario: Removing extra spaces from a user's message to ensure accurate


keyword matching.
● Example: user_input = " what is the time? " clean_input =
user_input.strip() # clean_input is "what is the time?"
.replace()
Robotic Manufacturing:
● Scenario: Correcting errors or modifying data in a log file.
● Example: log_entry = "STATUS: ERROR" corrected_entry
= log_entry.replace("ERROR", "FAILURE")
Chatbots:
● Scenario: Sanitizing user input or replacing common typos to
improve understanding.
● Example: user_input = "I need assistance for my
acct." cleaned_input = user_input.replace("acct",
"account")
.find() and .index()

Robotic Manufacturing:

● Scenario: Locating a specific pattern or identifier within a larger data string, such as
an RFID tag.
● Example: sensor_log = "Timestamp: 16:30, Part ID: P-101-B"
start_index = sensor_log.find("Part ID: ") if start_index !=
-1: # part ID found # Extract the part ID

Chatbots:

● Scenario: Finding the position of a specific command or keyword to perform a


context-aware action.
● Example: user_query = "I want to book a flight to Paris"
city_index = user_query.find("to") + 3 destination =
user_query[city_index:]
.isalnum() and .isdigit()
Robotic Manufacturing:
● Scenario: Validating that an input string, such as a serial number,
contains only numbers and letters.
● Example: serial_number = "A1B2C3" if
serial_number.isalnum(): print("Valid serial
number.")
Chatbots:
● Scenario: Verifying that a user's input for a numerical value (like an
age or a quantity) contains only digits.
● Example: user_age = "30" if user_age.isdigit(): #
process the age
.split()

Robotic Manufacturing:

● Scenario: Parsing data from a single string, such as a comma-separated list of


sensor readings.
● Example: sensor_data = "25.3,12.1,88.9" readings =
sensor_data.split(',') # readings is now ['25.3', '12.1',
'88.9']

Chatbots:

● Scenario: Breaking down a user's sentence into individual words to analyze


keywords o ar commands.
● Example: user_query = "Please find the nearest store" words =
user_query.split() # words is now ['Please', 'find', 'the',
'nearest', 'store']

You might also like