by BehindJava

What is a String in Python with Syntax and Examples

Home » python » What is a String in Python with Syntax and Examples

In this tutorial we are going to learn about String in Python and its examples.

Strings are used in Python to record text information, such as names. Strings in Python are actually a sequence, which basically means Python keeps track of every element in the string as a sequence. For example, Python understands the string “hello’ to be a sequence of letters in a specific order. This means we will be able to use indexing to grab particular letters (like the first letter, or the last letter).

This idea of a sequence is an important one in Python and we will touch upon it later on in the future.

In this lecture we’ll learn about the following:

  1. Creating String
  2. Printing String
  3. String Indexing and Slicing
  4. String Properties
  5. String Methods
  6. Print Formatting

Creating a String

“Hello”
       “2”(anything in quotes is a string)

Printing a String

print(‘hello’)
     Print(2)
   Print(I am pretty’)

We can use len() function to get the length of a string.

String Indexing

We know strings are a sequence, which means Python can use indexes to call parts of the sequence. Let’s learn how this works.

In Python, we use brackets [] after an object to call its index. We should also note that indexing starts at 0 for Python. Let’s walk through a few examples of indexing.

x=”hello”

Indexing:

  • To get the first letter of word-x[0]=h
  • To get the second letter of word-x[1]=e
  • To get the third letter of word-x[2]=l

String slicing

We can use a : to perform slicing which grabs everything up to a designated point.

  1. Grab everything past the first term all the way to the length of s which is len(s)

    s[1:]
  2. Grab everything UP TO the 3rd index

    s[:3](it doesn’t include third index)
  3. Everything

    s[:]
  4. Last letter (one index behind 0 so it loops back around)

    s[-1]
  5. Grab everything but the last letter

    s[:-1]
  6. Grab everything, but go in steps size of 1

    s[::1]
  7. Grab everything, but go in step sizes of 2

    s[::2]
  8. We can use this to print a string backwards

    s[::-1]

    String Properties

    It’s important to note that strings have an important property known as immutability. This means that once a string is created, the elements within it can not be changed or replaced.

Basic Built-in String methods: Objects in Python usually have built-in methods. These methods are functions inside the object (we will learn about these in much more depth later) that can perform actions or commands on the object itself.

We call methods with a period and then the method name. Methods are in the form:

object.method(parameters)

Where parameters are extra arguments we can pass into the method. Don’t worry if the details don’t make 100% sense right now. Later on we will be creating our own objects and functions!

Here are some examples of built-in methods in strings:

  1. Upper Case a string

    s.upper()
  2. Lower case

    s.lower()
  3. Split a string by blank space (this is the default)

    s.split()
  4. Split by a specific element (doesn’t include the element that was split on)

    s.split('W')

    String Methods

    Python has a set of built-in methods that you can use on strings.

Note: All string methods returns new values. They do not change the original string.

Method Description:

  • capitalize() Converts the first character to upper case
  • casefold() Converts string into lower case
  • center() Returns a centered string
  • count() Returns the number of times a specified value occurs in a string
  • encode() Returns an encoded version of the string
  • endswith() Returns true if the string ends with the specified value
  • expandtabs() Sets the tab size of the string
  • find() Searches the string for a specified value and returns the position of where it was found
  • format() Formats specified values in a string
  • format_map() Formats specified values in a string
  • index() Searches the string for a specified value and returns the position of where it was found
  • isalnum() Returns True if all characters in the string are alphanumeric
  • isalpha() Returns True if all characters in the string are in the alphabet
  • isdecimal() Returns True if all characters in the string are decimals
  • isdigit() Returns True if all characters in the string are digits
  • isidentifier() Returns True if the string is an identifier
  • islower() Returns True if all characters in the string are lower case
  • isnumeric() Returns True if all characters in the string are numeric
  • isprintable() Returns True if all characters in the string are printable
  • isspace() Returns True if all characters in the string are whitespaces
  • istitle() Returns True if the string follows the rules of a title
  • isupper() Returns True if all characters in the string are upper case
  • join() Joins the elements of an iterable to the end of the string
  • ljust() Returns a left justified version of the string
  • lower() Converts a string into lower case
  • lstrip() Returns a left trim version of the string
  • maketrans() Returns a translation table to be used in translations
  • partition() Returns a tuple where the string is parted into three parts
  • replace() Returns a string where a specified value is replaced with a specified value
  • rfind() Searches the string for a specified value and returns the last position of where it was found
  • rindex() Searches the string for a specified value and returns the last position of where it was found
  • rjust() Returns a right justified version of the string
  • rpartition() Returns a tuple where the string is parted into three parts
  • rsplit() Splits the string at the specified separator, and returns a list
  • rstrip() Returns a right trim version of the string
  • split() Splits the string at the specified separator, and returns a list
  • splitlines() Splits the string at line breaks and returns a list
  • startswith() Returns true if the string starts with the specified value
  • strip() Returns a trimmed version of the string
  • swapcase() Swaps cases, lower case becomes upper case and vice versa
  • title() Converts the first character of each word to upper case
  • translate() Returns a translated string
  • upper() Converts a string into upper case
  • zfill() Fills the string with a specified number of 0 values at the beginning

There are several ways to present the output of a program, data can be printed in a human-readable form, or written to a file for future use or even in some other specified form. Sometimes user often wants more control the formatting of output than simply printing space-separated values. There are several ways to format output.

  • To use formatted string literals, begin a string with f or F before the opening quotation mark or triple quotation mark.
  • The str.format() method of strings help a user to get a fancier Output.
  • Users can do all the string handling by using string slicing and concatenation operations to create any layout that the user wants. The string type has some methods that perform useful operations for padding strings to a given column width.

Formatting output using String modulo operator(%) :

# Python program showing how to use
# string modulo operator(%) to print
# fancier output
 
# print integer and float value
print("BJ : %2d, Portal : %5.2f" % (1, 05.333))
 
# print integer value
print("Total students : %3d, Boys : %2d" % (240, 120))
 
# print octal value
print("%7.3o" % (25))
 
# print exponential value
print("%10.3E" % (356.08977))

Output :

BJ :  1, Portal : 5.33
Total students : 240, Boys : 120
031
3.561E+02

Formatting output using the format method :

# Python program showing
# use of format() method
 
# using format() method
print('I love {} for "{}!"'.format('BJ', 'BJ'))
 
# using format() method and referring
# a position of the object
print('{0} and {1}'.format('BJ', 'Portal'))
 
print('{1} and {0}'.format('BJ', 'Portal'))
 
 
# the above formatting can also be done by using f-Strings
# Although, this features work only with python 3.6 or above.
 
print(f"I love {'BJ'} for \"{'BJ'}!\"")
 
# using format() method and referring
# a position of the object
print(f"{'BJ'} and {'Portal'}")

Output:

I love BJ for "BJ!"
BJ and Portal
Portal and BJ

The brackets and characters within them (called format fields) are replaced with the objects passed into the format() method. A number in the brackets can be used to refer to the position of the object passed into the format() method.

Formatting output using the String method :

The string type has some methods that help in formatting output in a fancier way. Some of method which help in formatting a output are str.ljust(), str.rjust(), str.centre()

# Python program to
# format a output using
# string() method
 
cstr = "I love bjforbj"
   
# Printing the center aligned 
# string with fillchr
print ("Center aligned string with fillchr: ")
print (cstr.center(40, '#'))
 
# Printing the left aligned 
# string with "-" padding 
print ("The left aligned string is : ")
print (cstr.ljust(40, '-'))
 
# Printing the right aligned string
# with "-" padding 
print ("The right aligned string is : ")
print (cstr.rjust(40, '-'))

Output:

Center aligned string with fillchr: 
##########I love bjforbj##########

The left aligned string is : 
I love bjforbj--------------------

The right aligned string is : 
--------------------I love bjforbj