Strings

Python String

What are Python Strings?

  • Python Strings are a sequences of characters used to represent text.
  • Enclosed in single quotes (') or double quotes (").
  • Immutable: Once created, their contents cannot be changed directly.

Python String Key Points


You should learn following important points, if you are new to Python String.
  1. Creating Strings
  2. Accessing Characters
  3. Slicing Strings
  4. String Concatenation
  5. String Formatting
  6. Common String Methods

1. Creating Strings

name = "Kuntal"
greeting = 'Hello !!!'
long_msg = """This is a multiline
   string using triple quotes."""
print(greeting)
print(name)
print(long_msg)

Output:

Hello !!!
Kuntal
This is a multiline
string using triple quotes.

2. Accessing Characters


first_char = name[0]  # Access first character
last_char = name[-1]  # Access last character
print(first_char)
print(last_char)

Output:

K
l

3. Slicing Strings
substring = greeting[0:2]  # Extract "He from Hello !!!"
print(substring)

Output:
He

4. String Concatenation

full_message = greeting + " " + name
print(full_message)

Output:
Hello !!! Kuntal


5. String Formatting

age = 40
formatted_text = "My name is {} and I am {} years old.".format(name, age)
print(formatted_text)

Output:

My name is Kuntal and I am 40 years old.


6. Common String Methods

print(name.upper())   # Convert to uppercase
print(greeting.lower())  # Convert to lowercase
print(long_msg.splitlines())  # Split into a list of lines

Output:

KUNTAL
hello !!!
['This is a multiline', ' string using triple quotes.']


Additional Notes:

  • Escape Sequences: Use backslashes (\) to represent special characters like newlines (\n) and tabs (\t).
  • Raw Strings: Prefix a string with r to ignore escape sequences: r'This string\nhas no newline'

Python is very good in String Processing. Strings can be enclosed in single quotes like 'PythonPracticals' or double quotes like "PythonPracticals".

>>> 'Python Practicals'  # single quotes
'Python Practicals'

>>> "Python Practicals"  # double quotes
'Python Practicals'


Observe the following code:

>>> 'Python's Practicals'
SyntaxError: invalid syntax

Reason of Error in above statement:

String starts at first single quote (') and ends at second single ('); hence above statement will result in error. The correct way of printing single quote (') in string is as under:


# Use \' to print single quote

>>> 'Python\'s Practicals' 
"Python's Practicals" 

#Another way to print ‘ is use double quote

>>> "Python's Practicals" 
"Python's Practicals"

# Following two statements will produce same output 

>>>'"Yes, you are correct"'
'"Yes, you are correct"' 

>>> '\"Yes, you are correct\"'
'"Yes,you are correct"'

# To print string without start and end quote, use print( )

>>> print("Yes, you are correct")
Yes, you are correct

print() function

Python print() function produces a more readable output; it will omits the enclosing quotes while printing output as shown below:

#Use print() function to avoid quotes in output string

>>> print("PythonPracticals.Blogspot.Com")
PythonPracticals.Blogspot.Com


Multi line String output using Newline character

>>> print("Python\nPracticals\n.Blogspot\n.Com")
Python
Practicals
.Blogspot
.Com

# Note: \n is a newline character

If you don’t want special characters (\n) to be interpreted as newline character, you can use raw strings by adding an r before the first quote as shown below:

# In following statement \n means newline

>>> print('C:\python\new’)
C:\python
ew

# r will remove the effect of \n

>>> print(r'C:\python\new')  
C:\python\new

Multi line String output using Paragraph format

String can span across multiple lines. One way of doing this is use triple-quotes: """...""" or '''...'''. End of line ( \n ) is automatically included in the string:

>>> print("""Hello
Students
How are you?
""")
Hello
Students
How are you?

Read more Python String Handouts
* * * * *

< Back to Home Page >


No comments:

Post a Comment