codescracker


python

Python Strings



« Previous Tutorial Next Tutorial »


Strings are contiguous set of characters in between quotation marks. You are free to use either pairs of single or double quotes to use the strings in your python program.

Python String Example

Here is an example of creating string in python:

str1 = 'Hello Python'
str2 = "This is Python Strings Tutorial"

To print the above created string as output. Then here is the code:

# Python Strings - Example Program

str1 = 'Hello Python'
str2 = "This is Python Strings Tutorial"

print(str1, "\n", str2);

Here is the output produced by the above python program:

python strings

Here is another example, demonstrates the concept and use of string in python:

# Python String - Example Program

str = 'Hello Python'

print (str)             # this will print the complete string
print (str[0])          # this will print the first character of the string
print (str[2:8])        # this will print the characters starting from 3rd to 8th
print (str[3:])         # this will print the string starting from the 4th character
print (str * 3)         # this will print the string three times
print (str + "String")  # this will print the concatenated string

Here is the sample output of the above python program:

python string example

Python Escape Sequence Characters

Here the following table lists the escape sequence character code and their name available in python:

Escape Sequence Character Code Output
\a Alert Bell
\cx Control-x
\b Backspace
\C-x Control-x
\f Formfeed
\e Escape
\M-\C-x Meta-Control-x
\r Carriage return
\n Newline
\nnn Octal notation
\s Space
\x x
\t Tab
\v Vertical tab
\xnn Hexadecimal notation

More Examples

Here are the list of some more examples on strings in python:


« Previous Tutorial Next Tutorial »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test