Python Strings Unit1

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 12

Strings

Creating and Sorting Strings:

Strings consist of one or more characters surrounded by matching quotation marks.


Strings are surrounded by either
• Single or double quotation marks.
• A string enclosed in double quotation marks can contain single quotation marks and vice
versa.
• If you have a string spanning multiple lines, than it can be included within triple quotes.
• You can find the type of a variable by passing it as an argument to type() function.
• Python strings are of str data type.

1. The str() Function:


• Str() function returns a string and the syntax for str() function is str(object).
• It returns a string version of the object.
• >>> str(10)
• ‘10’
• >>>create_string=str()
• >>>type(create_string)
• <class ‘str’>
• Here integer 10 is converted to string. The create_string is an empty string of type str.
2. Basic String Operations:
In Python, strings can also be concatenated using + sign and * operator is used to create a repeated sequence of
strings

>>>string_1 =“face”
>>>string_2 =“book”
>>>string_1+string_2
‘facebook’
When two strings are concatenated, there is no white space between them. If you need a white space between
the 2 strings, include a space after the first string or before the second string within the quotes.
>>>singer = 50+”cent” gives an error as 50 is of integer type and cent is of string type.
>>>singer =str(50) + “cent”
>>>singer
‘50cent’
>>>repeated_str =“wow” * 5
>>>repeated_str
‘wowwowwowwowwow’
You can check the presence of a string in another string using in and not in membership operators
>>>fruit_str=“apple is a fruit”
>>>fruit_sub_str=‘apple’
>>>fruit_sub_str in fruit_string
True
>>> another_fruit_str=“orange”
>>>another_fruit_str not in fruit_str
True
3. String Comparison:
>, <, <=,>=,==, != can be used to compare two strings resulting in True or False. Python compares
the strings using ASCII value of the characters.
>>>”january” == “jane”
False
>>>”january” != “jane”
True
>>>”january” > “jane” # the ASCII value of u is more than e
True
>>>”january” < “jane”
False
>>>”january” >= “jane”
True
>>>”january” <= “jane” Built in functions Descriptions
False Len() This function calculates the number
>>>”filled”>”” of characters in a string
True
4. Built In Functions
Max() This function returns a character
having highest ASCII value
using Strings
There are built in functions for Min() This function returns a character
which a string can be passed having lowest ASCII value
as an argument.
Eg:
>>>max(“axel”)
‘x’
>>>min(“brad”)
‘a’
5. Accessing Characters in String by Index Number:
Each character in the string occupies a position in the string. Each of the string’s character
corresponds to an index number. First character is at index 0.
Syntax: string_name[index]

b e y o u r s e l f
>>>word_phrase=“be yourself”
0 1 2 3 4 5 6 7 8 9 10
index
>>>word_phrase[0]
‘b’
>>>word_phase[1]
e
>>>word_phase[2]
‘’
>>>word_phase[3]
y
The individual characters in a string can be accessed using negative indexing. If there is a long string and you want
to access end characters in a string, then you can count backwards from the end of the string starting from
the index of -1

>>>word_phrase[-1]
‘f’
>>>word_phrase[-2]
b e y o u r s e l f
‘l’ index -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

6. String Slicing and Joining

The syntax for string slicing is,


String_name[start:end[:step]]
You can access a sequence of characters by specifying a range of index numbers separated by a colon. The string
slicing starts from the beginning and extending up to but not including end. After slicing substring is created.
>>>drink =“green tea”
>>>drink[0:3]
‘gre’
>>>drink[:5]
‘green’ g r e e n t e a
>>>drink[6:] 0 1 2 3 4 5 6 7 8
‘tea’
>>>drink[:]
‘green tea’
>>>drink[6:20]
‘tea’
A substring is a sequence of characters contained in a string.
If start index and end index are omitted, then the entire string is displayed
If the start index is equal to or higher than end index, result is an empty string.
Slicing can be done using negative integer numbers.

>>>drink[-3:-1]
‘te’ g r e e n t e a
>>>drink[6:-1]
-9 -8 -7 -6 -5
‘te’ We can combine the positive and negative indexing numbers
-4 -3 -2 -1

7. Specifying steps in Slice Operation:


Steps refers to the number of characters that can be skipped after the start indexing character in
the string. Default value of step is one.
>>>newspaper=“new York times”
>>>newspaper[0:12:4]
‘ny’
>>>newspaper[::4]
‘ny e’
Starts with index 0 and till n and will print every 4 th character.

8. Joining Strings using Join() Method


8. Joining Strings using Join() Method:
Strings can be joined with join() string. Join() method syntax is,
String_name.join(sequence)
If sequence is a string, then join() function inserts string_name between each item of list
sequence and returns the concatenated string.
>>>date_of_birth=[“17”,”09”,”1950”]
>>>”:”.join(date_of_birth)
‘17:09:1950’
>>>numbers=‘123’
>>>characters = ‘amy’
>>>password = numbers:join(characters)
>>>password
‘a123m123y’
The string value of ‘123’ is inserted between a and m and again between m and y and is assigned
to password string variable.

9. Split Strings using split() Method:


The syntax is
string_name.split([separator [, maxsplit]])
If the seperator is not specified, then whitespace is considered as the delimiter string.
Eg:
>>>shoes = “ Nike Puma Adidas Bata Liberty”
>>>shoes.split()
>>>icecream=“vanilla, black current, strawberry, chocolate”
>>>icecream.split(“,”)
The string icrecream is split with the seperator as ,. If seperator is not specified, whitespace is
used by default.
10. Strings are immutable:
The characters in a string cannot be changed once it is assigned to string variable.
>>>stringVar = “Hello”
>>>stringVar[0] = “c” // this line gives an typeerror saying str object does not support item
assignment
11. String Traversing:
Each of the characters in a string can be traversed using the for loop.
Eg:
def main():
stringVar = “KLESNC”
index = 0
for each_character in stringVar:
print(f”Character ‘{each_character}’ has an index value of {index}”)
index+=1
12: String Methods
All the methods supported by string can be found using the dir command.
>>>dir(str)

COPY METHODS from TEXT Book


13. Formatting Strings:
The strings can be formatted in the below ways:
a) %-formatting : Only str, int and doubles can be formatted. All other types are not supported
or converted to one of these types before formatting. Also it does not work with multiple
values.
b) Eg:
• >>>TestVar = ‘KLESNC’
• >>>’College : %s’ % TestVar
• ‘College : KLESNC’
• >>>TestVar = (‘KLESNC’, 560010)
• >>>’College : %s’ % TestVar
TypeError: not all arguments converted during string formatting.
b) Str.format:
This was added to address some of these problems with %-formatting.
Eg:
>>>value = 5 * 10
>>>’The value is {value}.’.format(value = value)
‘The value is 50.’
Too much Verbosity.
c) f-strings provide a concise, readable way to include the value of Python expressions inside
strings.
eg:
>>>f”The value is {value}’.

You might also like