0% found this document useful (0 votes)
37 views4 pages

Strings

This document discusses strings in Python. It begins by defining a string as a sequence of characters and notes they are created using the str constructor or enclosing characters in quotes. It then provides details on indexing characters in a string using brackets, slicing strings to extract substrings, concatenating and repeating strings with operators, comparing strings, and iterating over the characters. The document also lists some common built-in string methods like len(), count(), find(), lower(), and upper().

Uploaded by

Kaan
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)
37 views4 pages

Strings

This document discusses strings in Python. It begins by defining a string as a sequence of characters and notes they are created using the str constructor or enclosing characters in quotes. It then provides details on indexing characters in a string using brackets, slicing strings to extract substrings, concatenating and repeating strings with operators, comparing strings, and iterating over the characters. The document also lists some common built-in string methods like len(), count(), find(), lower(), and upper().

Uploaded by

Kaan
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
You are on page 1/ 4

12/14/2021

Strings
 Functions for strings
KMM102E  Indexing characters in a string : Index operator [ ]
INTRODUCTION TO COMPUTER PROGRAMMING  The slicing operator [start : end]
IN PYTHON  The concatenation (+) and repetition (*) operators
 in and not in operators
Strings  Comparing strings
 Iterating characters in a string
 Built-in string operations
A string is a sequence of characters.  Common operations on strings
 String module
In programming languages, any sequence of printable characters is
referred to as a "string".

Strings are created with the constructor str or by enclosing characters


with a pair of quotes.

Strings Strings
Strings are fundamental in computer science, and processing strings is a common task in programming.  Indexing characters in a string : Index operator [ ]
Strings are the objects of the str class. So far, strings are used in input and output. A string is a collection type that has multiple parts. A string is a sequence of characters.
 The input function returns a string from the keyboard
The position of a character within a string object is called as index. A character in the string can therefore
 The print function displays a string on the monitor.
be accessed through the index operator using the syntax of:
A string object is immutable: once it is created, its individual character cannot be changed. s[index]
A string variable content can be replaced by another string content, but a part of it can not be changed!
The indexes are 0 based; that is, they range from 0 to len(s)-1.

s = "Programming is fun"
 Functions for strings
Several of Python’s built-in functions can be used with strings.
 len : It can be used to return the number of the characters (individual characters) in a string.
 max : It can be used to return the largest character in a string. The characters in a string can be accessed via an index operator.
 min : It can be used to return the smallest character in a string.

Space is the smallest character !


12/14/2021

Strings Strings
 The slicing operator [start : end]  The concatenation (+) and repetition (*) operators
The slicing operator returns a slice of the string using the syntax s[start : end]. In string operations, it is possible
 join, or concatenate, two strings by using the concatenation operator (+).
 Python uses a half-open range concept. A half-open range designates the beginning of the
 use the repetition operator (*) to concatenate the same string multiple times.
sequence that is included in the result along with an end of the sequence that is not included.
 The slice is a substring from index start to index end – 1.
s[1 : 4] returns a substring from index 1 to index 3.  rog
s[ : 6 ] returns a substring from the first index (0) to index 5.  Progra
s[12 : ] returns a substring from 12 to the last index (len(s)-1).  is fun

Negative indexing could also be used in slicing. Negative index works back from the end.  in and not in operators
These operators can be used in a program to check whether a string is in another string.
s[-1]  n (last character)
s[12:-1]  is fu

Slicing allows a third parameter that specifies the step in the slice. This means that one can have as many
as three numbers in the index operator brackets separated by two colon characters: the first number is the
beginning of the sequence, the second number specifies the end of the sequence, and the third is the step
to take along the sequence. s[ : : 2]  Pormigi u ; s[ 2:10: 3]  oai

Strings Strings
 Comparing strings  Iterating characters in a string
Strings can be compared by using the comparison operators (==, !=, >, >=, <, <=).
A string is iterable.
 Python compares strings by comparing their corresponding characters in UTF-8 character set table.
 Comparison performed based on the numeric codes for characters.  Each character in the string object can be accessed by a for loop (or other methods) sequentially.

Example:
a is larger than A because the numeric code for "a" is larger than the numeric code for "A".

 Built-in string operations


All string operations can be seen by entering the following line in the Shell:
>>> dir("abc")
12/14/2021

Strings Strings
 Built-in string operations  Built-in string operations
Python provides many built-in operations that allow you to manipulate a string object. The syntax of these
Most Commonly Used Built-In String Operations
operations is a little different from what we have seen before. This is the general syntax:
string_object.operation( required and/or optional argument(s) ) Operation Description

Using such structures in Python is also called as method. A method is a variation on a function. Every string_object.count(x) Returns the number of times x was found in string_object.
method is called in conjunction with a particular object. string_object.find(x) Returns the index of the first occurrence of x in string_object. Returns –1 if x is not found.
string_object.index(x) Returns the index of the first occurrence of x in string_object.
string_object.lower() Returns a lowercase version of string_object.
Object is an expression that represents object, such as the name of a string expression s. string_object.upper() Returns an uppercase version of string_object.
The period, pronounced dot, associates an object expression with method to be called. string_object.title()
Returns a version of string_object where the first letter of every word is uppercased, all other letters
are lowercased
Method name is the name of the method to execute. string_object.lstrip() Returns the string_object with leading (left) whitespace removed
The parameter list is comma-separated list of parameters to the method. For some methods the string_object.rstrip() Returns the string_object with trailing (right) whitespace removed
parameter list may be empty, but the parenthesis always are required, because method applied is a string_object.strip() Returns the string_object with leading and trailing whitespace removed
special function that could be considered as used defined function specific to the object focused!). string_object.replace(x_old,x_new) Returns a version of string_object where all x_old are replaced by x_new
string_object.startswith(x_prefix) Returns True if string_object starts with x_prefix, otherwise returns False
The kinds of methods that can be used in conjunction with an object depends on the object’s type.
String objects have a set of methods suited for strings.
s = "fun"
print ( s.upper() )  FUN
print ( s.find("f"), s.find("x") )  0 -1

Strings Strings
 Built-in string operations  Common operations on strings
Substring specification : s[i:j] extracts the substring starting with character number i and ending with number j-1
Searching for substrings :
 s.find(s1) -> result is an integer value…returns the lowest index where s1 starts in s, or -1 if s1 is not found in s
 s.rfind(s1) -> result is an integer value…returns the highest index where s1 starts in s, or -1 if s1 is not found in s
 s.count(s1) -> result is an integer value…returns the number of non-overlapping occurrence of s1
 s.startswith(s1) -> result is boolean ( T or F)..returns True if the s starts with s1
 s.endswith(s1) -> result is boolean ( T or F)..returns True if the s ends with s1
Converting strings :
 s.capitalize() -> result is string…returns a copy of s with only the first character capitalized.
 s.lower() -> result is string…returns a copy of s with all letters converted to lowercase.
 s.upper() -> result is string…returns a copy of s with all letters converted to uppercase.
 s.title() -> result is string…returns a copy of s with the first latter capitalized in each word.
 s.swapcase() -> result is string…returns a copy of s in which lowercase letters are converted to uppercase and uppercase to lowercase.
 s.replace(s1, s2) -> result is string..returns a new string that replaces all the occurrences of the s1 with a new s2

Testing strings :
 s.isalnum() -> result is boolean ( T or F)..returns True if characters in s are alphanumeric and there is at least one character.
 s.isalpha() -> result is boolean ( T or F)..returns True if characters in s are alphabetic and there is at least one character.
 s.isdigit() -> result is boolean ( T or F)..returns True if s contains only number characters.
 s.isidentifier() -> result is boolean ( T or F)..returns True if s is a Python identifier.
 s.islower() -> result is boolean ( T or F)..returns True if all characters in s are lowercase letters and there is at least one character.
 s.isupper() -> result is boolean ( T or F)..returns True if all characters in s are uppercase letters and there is at least one character.
 s.isspace() -> result is boolean ( T or F)..returns True if s contains only whitespace characters.
12/14/2021

Strings Strings
 Common operations on strings  String module
Stripping whitespace characters from a string : Characters " ", \t, \f, \r, \n are called the whitespace characters.
 s.strip(s1) -> result is string..returns a string with the starting and trailing whitespace characters removed.
 s.lstrip(s1) -> result is string..returns a string with the leading whitespace characters removed.
 s.rstrip(s1) -> result is string..returns a string with the trailing whitespace characters removed.
String splitting :
 s.split() splits the string s into words separated by whitespace (space, tabulator, or newline)
 s.split(t) splits the string s into words separated by a text t where it could be any string such as ":", "/", "abc" etc.
 s.splitlines() a multi-line string is split into lines

String joining : The opposite of the split method is join, which joins elements in a list of strings with a specified delimiter in between.
 delimiter.join() delimiter could be " " or "," or ";" or "/" etc.
Formatting strings :
 s.center(width) -> result is string..returns a copy of s centered in a field of the given width.
 s.ljust(width) -> result is string..returns a string left justified in a field of the given width.
 s.rjust(width) -> result is string..returns a string right justified in a field of the given width.
 s.format(width) -> result is string..formats a string.

Strings
 Examples

Write a program checking whether a word is palindrome. Program should:


 prompt the user to enter a string
 report whether the string is palindrome.

A string is palindrome if it reads the same forward and backward.


The words mom, dad, noon are all palindromes.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy