Skip to content

Python Journey

My Coding Blog

Menu
  • Links
Menu

Python>>Data Type:Strings

Posted on August 23, 2022 by coden00b

Strings are text type and are sequences of character data. It is represented by quotation marks, either single or double quotes.

Example:

“Hello”

‘What is your name?’

>>> “Hello”
‘Hello’
>>> x = ‘What is your name?’
>>> print (x)
What is your name?
>>>

Some key notes:

1.Escape sequences in strings = use backslash (\) character

Examples:

 

>>> print (‘This is a single quote symbol \’ ‘)
This is a single quote symbol ‘
>>> print (‘This is a single quote symbol (\’)’)
This is a single quote symbol (‘)
>>> print (“This is a single quote symbol (\’)”)
This is a single quote symbol (‘)
>>> print (‘I’m handsome’)
  File “<stdin>”, line 1
    print (‘I’m handsome’)
              ^
SyntaxError: invalid syntax
>>> print (‘I\’m handsome’)
I’m handsome
>>> x = “I am the \”King\” of this land”
>>> print (x)
I am the “King” of this land
>>> print (‘This is a backslash symbol \\’)
This is a backslash symbol \
Other popular escape characters:
\n = new line
\t = tab
>>> print (‘test \n only’)
test
 only
>>> print (‘test \t only’)
test     only

2. Since it is a sequence, can use indexing and slicing for the subsets of strings using the slice operator  ([ ] and [:] ). Indexes starting “0” in the start of the string.

Example:
Character: E  u  a  n
Index:        0  1  2  3
Neg Index:-4 -3 -2 -1
>>> x = “Euan”
>>> print(x[0])
E
>>> print(x[3])
n
>>> print(x[-3])
u
>>> print(x[-4])
E
For slicing, it lets you access parts of the sequence, normally we use it if we want to get the part of the string and not the complete string.
Syntax:
string[start : end : step]
where:
start = starting index
end = end index (not included in substring,go up to but don’t include it)
step=optional argument determining the increment between each index for slicing
Example:
W r  i  t  e c o d e
 0 1 2 3 4  5 6 7 8
You only want to get the word code in this string (remember the indexing concept

>>> x =”Writecode”
>>> print(x)
Writecode
>>> print (x[5:])
code

So if you want to get the word “Write”, then you can do this way
>>> print (x[:5])
Write
How about middle?example we want to take word “teco”
>>> print (x[3:7])
teco
More indexing and slicing for next post.

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Recent Posts

  • Python Project1: Guess Number
  • The Zen of Python
  • Python>>String Interpolation and Formatting
  • Python>>String Methods
  • Python>>String Concatenation

Archives

  • December 2024
  • January 2023
  • August 2022

Tags

.format attributes concatenation count data type find float fstring guess indexing interpolation len lower methods number project python random replace slicing string strings template time upper zen
© 2025 Python Journey | Powered by Minimalist Blog WordPress Theme
Menu
  • Links