Python Strings Unit1
Python Strings Unit1
Python Strings Unit1
>>>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
>>>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