• Skip to main content
  • Skip to primary sidebar
  • Skip to secondary sidebar
  • Skip to footer

Computer Notes

Library
    • Computer Fundamental
    • Computer Memory
    • DBMS Tutorial
    • Operating System
    • Computer Networking
    • C Programming
    • C++ Programming
    • Java Programming
    • C# Programming
    • SQL Tutorial
    • Management Tutorial
    • Computer Graphics
    • Compiler Design
    • Style Sheet
    • JavaScript Tutorial
    • Html Tutorial
    • Wordpress Tutorial
    • Python Tutorial
    • PHP Tutorial
    • JSP Tutorial
    • AngularJS Tutorial
    • Data Structures
    • E Commerce Tutorial
    • Visual Basic
    • Structs2 Tutorial
    • Digital Electronics
    • Internet Terms
    • Servlet Tutorial
    • Software Engineering
    • Interviews Questions
    • Basic Terms
    • Troubleshooting
Menu

Header Right

Home » Python » Python String Variables
Next →
← Prev

Python String Variables

By Dinesh Thakur

Python can manipulate string, which can express in several ways. String literals can be enclosed in matching single quotes(‘) or double quotes(“); e.g. ‘hello’, “hello” etc. They can also enclose in matching groups of three single or double quotes (these generally referred to as triple quoted strings), e.g.” ‘hello”’, “””hello”””. A string is enclosed in double-quotes if the string contains a single quote (and no double quotes); it encloses in single quotes.


String type variables store strings as names and texts in general. We call string a sequence of symbols such as letters, numbers, punctuation marks, special characters, and spaces. For example: “I see my cat” in this example every sentence is a sequence of letters (I, ,s,e,e, ,m,y, ,c,a,t). We can imagine a string as a sequence of blocks, where each letter, number, or blank space occupies a position as shown.

String

I

 

s

e

e

 

m

y

 

c

a

t

To use the text of your program and the contents of a string, we use double quotes (“) or single (‘) to delimit the beginning and end of the string.

Assigning a string to a variable of type string (% s):

# String type used mask %s
phrase = "I see my cat"
print ("Quote: % s" %phrase)

Another feature of strings can access the character of its contents by character. Knowing that a string has a specific size allows you to access their characters using an integer to represent their position. This number is called index and started counting at zero. It means that the string’s first character will always be in the position or index (zero).

0

1

2

3

4

5

6

7

8

9

10

11

Index

I

 

s

e

e

 

m

y

 

c

a

t

Contents

To access the string characters, we must inform the index or position of the character in square brackets ([]). As the first character of a string is index 0, we can access values from 0 to the length of the string minus 1. As in the above example, the string contains 12 characters and can access the position 0..11.

name = "Dinesh Thakur"
print (name [0])  # Position at index 0

If you try to access an index higher than the number of characters in the string, the Python interpreter will issue an error message.

We’ll be covering the following topics in this tutorial:

  • Python Concatenation String
  • Python Slicing String
  • String constants

Python Concatenation String

Concatenation can join two or more strings into a new larger string or sometimes smaller minor cases. For example, when we have a very large person’s name, and our layout fits fewer characters than the name contain.
The content of the string type variables can add, or rather concatenated. To concatenate two strings, use the plus (+) operator. Thus, “ABC” + “D” is equal to “ABCD”. A special concatenation case is the repetition of a string several times. For this, we use the multiplication operator (*), “D” * 5 equals “DDDDD.”

char = "abc"
   # Concatenated the character, together presenting the variable char
print (char + "c")
   # Concatenated the character D, together presenting the variable char
print (char + "D" * 4)
   # Concatenated the character Z, and 10 (-) with the character X
print ("Z" + "-" + 10 * "X")
   # Concatenated the variable (char), (z4 =), 4 times (char)
print (char + "z4 =" + char * 4 )

Python Slicing String

Slicing in Python is very important. Imagine our string, “I see my cat,” who was working in class 4. We can slice it to write only the first word, second, third, or even want to use only the first three letters of the string by accessing the indices [0: 5]. It is the string slicing. The number left of the points indicates the start position and the right end of the slice.

phrase = "I see my cat"
print (phrase [0: 5])

 

However, care should be taken at the end, as in the previous example we use the 5, which is in position 6 was not included. It is because the end of slicing not include, left out.

char = "abcdefgh"
   print(char[2:])
   >>> 
   cdefgh

You can also omit the number left or right to represent the beginning of the end. So [: 3] indicates the beginning to the third character (without including it), and [2:] means the position of the second character to the end of the string, as shown above. Note that, in this case, not need to know how many characters the strings have.

char = "abcdefgh"
   print(char[:])
   >>> 
   Abcdefgh

If we omit the beginning and end of slicing, we are merely making a copy of all the string characters, as shown above.
We can also use negative values to indicate positions from the right. So in the last character -1, -2, the penultimate, and so on. Follow the examples below:

char = "abcdef"
  print (char [: 2])
  print (char [1:])
  print (char [0: -2])
  print (char [:])
  print (char [-1:])
  print (char [-2: -1])
  print (char [-3: -1])

 

This content is significant when you have to assemble reports, presentation layouts, and no physical space to display the information stored.

String constants

Some constants defined in string module are as follows:

string.ascii_lowercase

It returns string containing lowercase letters ‘abcdefghijklmnopqrstuvwxyz ‘.

>>>import string
>>>string.ascii_lowercase
'abcdefghijklmnopqrstuvwxyz'

string.ascii_uppercase

It return string containing uppercase letters ‘ABCDEFGHIJKLMNOPQRSTUVWXYZ ‘.

>>>string.ascii_uppercase
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

string.ascii_letters

It returns string containing concatenation of the ascii_lowercase and ascii_uppercase constants.

>>>string.ascii_letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'

string.digits

It returns the string containing digits ‘0123456789 ‘.

>>> string.digits
'0123456789'

string.hexdigits

It returns the string containing hexadecimal characters ‘0123456789abcdefABCDEF’.

>>> string.hexdigits
'0123456789abcdefABCDEF'

string.octdigits

It returns the string containing octal characters ‘ 01234567 ‘.

>>>string.octdigits
'01234567'

string.punctuation

It returns the string of ASCII characters which are considered punctuation characters.

>>>string.punctuation
I!"#$%&\'()*+,-./:;<=>[email protected][\\]"_' {I}-'

string.whitespace

It returns the string containing all characters that are considered whitespace like space, tab, vertical tab etc.

>>>string.whitespace
'\t\n\x0b\x0c\r '

string.printable

It returns the string of characters which are considered printable. This is a combination of digits, letters, punctuation, and whitespace.

>>> string.printable
'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&
\' ()*+,-./:;<=>[email protected][\\]"_' {I}- \t\n\r\x0b\x0c'

You’ll also like:

  1. Python String maketrans() Method
  2. Python String rfind() Method
  3. Python String index() Method
  4. Python String isspace() Method
  5. Python String startswith() Method
Next →
← Prev
Like/Subscribe us for latest updates     

About Dinesh Thakur
Dinesh ThakurDinesh Thakur holds an B.C.A, MCDBA, MCSD certifications. Dinesh authors the hugely popular Computer Notes blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps.

Dinesh Thakur is a Freelance Writer who helps different clients from all over the globe. Dinesh has written over 500+ blogs, 30+ eBooks, and 10000+ Posts for all types of clients.


For any type of query or something that you think is missing, please feel free to Contact us.


Primary Sidebar

Python

Python Tutorials

  • Python - Home
  • Python - Features
  • Python - Installation
  • Python - Hello World
  • Python - Operators Types
  • Python - Data Types
  • Python - Variable Type
  • Python - Switch Case
  • Python - Line Structure
  • Python - String Variables
  • Python - Condition Statement
  • Python - if else Statement
  • Python - for-loop
  • Python - while loop
  • Python - Command Line
  • Python - Regular Expression

Python Collections Data Types

  • Python - List
  • Python - Sets
  • Python - Tuples
  • Python - Dictionary

Python Functions

  • Python - Functions
  • Python - String Functions
  • Python - Lambda Function
  • Python - map() Function

Python Object Oriented

  • Python - Oops Concepts
  • Python - File Handling
  • Python - Exception Handling
  • Python - Multithreading
  • Python - File I/O

Python Data Structure

  • Python - Linked List
  • Python - Bubble Sort
  • Python - Selection Sort
  • Python - Linear Search
  • Python - Binary Search

Python Programs

  • Python - Armstrong Number
  • Python - Leap Year Program
  • Python - Fibonacci Series
  • Python - Factorial Program

Other Links

  • Python - PDF Version

Footer

Basic Course

  • Computer Fundamental
  • Computer Networking
  • Operating System
  • Database System
  • Computer Graphics
  • Management System
  • Software Engineering
  • Digital Electronics
  • Electronic Commerce
  • Compiler Design
  • Troubleshooting

Programming

  • Java Programming
  • Structured Query (SQL)
  • C Programming
  • C++ Programming
  • Visual Basic
  • Data Structures
  • Struts 2
  • Java Servlet
  • C# Programming
  • Basic Terms
  • Interviews

World Wide Web

  • Internet
  • Java Script
  • HTML Language
  • Cascading Style Sheet
  • Java Server Pages
  • Wordpress
  • PHP
  • Python Tutorial
  • AngularJS
  • Troubleshooting

 About Us |  Contact Us |  FAQ

Dinesh Thakur is a Technology Columinist and founder of Computer Notes.

Copyright © 2023. All Rights Reserved.