Home » Python programs

Python | Access and print characters from the string

Here, we are going to learn how to access and print characters from the string in Python? We will print characters by index.
Submitted by IncludeHelp, on August 01, 2018

Given a string, we have to access characters from the string in Python.


    str: "Hello world"

    First character: H
    Second character: e
    Last character: d
    Second last character: l
    Characters from 0th to 4th index: Hello
    And, so on...


# access characters in string

# declare, assign string 
str = "Hello world"

# print complete string
print "str:", str

# print first character 
print "str[0]:", str[0]

# print second character 
print "str[1]:", str[1]

# print last character
print "str[-1]:", str[-1]

# print second last character
print "str[-2]:", str[-2]

# print characters from 0th to 4th index i.e.
# first 5 characters
print "str[0:5]:", str[0:5]

# print characters from 2nd index to 2nd last index
print "str[2,-2]:", str[2:-2]

# print string character by character
print "str:"
for i in str:
	print i,
#comma after the variable
# it does not print new line


    str: Hello world
    str[0]: H
    str[1]: e
    str[-1]: d
    str[-2]: l
    str[0:5]: Hello
    str[2,-2]: llo wor
    H e l l o   w o r l d

Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.

Quick links
Latest articles, Internship, Members
Coding problems, Algorithms, Discrete Mathematics, Big data
C, C++, C++ STL, Java, Data Structure, C#.Net, Android, Kotlin, SQL
PHP, Python, JavaScript, CSS, Ajax, Node.js, Web prog.
C, C++, DS, Java, C#, Python
C, C++, Java, DBMS
C, Embedded C, Java, SEO, HR
CS Subjects
CS Basics O.S. Networks DBMS Embedded Systems Cloud Computing Machine learning CS Organizations Linux DOS
Articles, Puzzles, News/Updates

Recommended posts
C Tips & Tricks, C++ Tips & Tricks
Introduction to Linux (Its modes, Safety, Most popular Applications)
Linux Best Distros of 2018
C programming optimization techniques
Differences b/w C & Embedded C?
Embedded C Interview Q. & A.
C programming tips for Embedded Development
Basic rules of writing a C program
Important points (rules) to remember while writing C/C++ program
Top 5 Websites for solving programming challenges

Computer G.K. (MCQ)
Most viewed pages...

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.