You are here

Strings and Lists in Python

Strings

Strings can be :

  1. Single quoted   : ‘Hello! I am here’. This is a single quoted string
  2. Double quoted : “Hello! i am here”. This is double “” quoted string.  Anything including escape sequence appear as it is, they are overridden
  3. Escape sequence be used anywhere (\n, \t, \a, \b and so on)
  4. Without print() string appear as it is, but with print () escape sequence have meaning

In Python, single-quoted strings and double-quoted strings are the same.  Pick a rule and stick to it.

Improving readability

When a string contains single or double quote characters, however, use the other one to avoid backslashes in the string. It improves readability.

Example:

2.1 String

We can use raw string with ‘r’ in print() function as:

2.2 Strings

Problems working with strings

In many cases, it has been seen that when you want to print a string or you want to work with a string, you may face the problem when there are one or more quotes in that string.

If you use the below code:

print(‘hello I don’t like single quote at all’)

The output will be:

print(‘hello I don’t like single quote at all’)

^

SyntaxError: invalid syntax

Because of that single quote, you will get an error like this.

don’t – here just because of this single quote we are getting an error. So we need to escape from this single quote.

Solutions:

  1. Put the string in between double quotes instead of single quotes.

print(“hello I don’t like single quote at all”)

Output:

hello I don’t like single quote at all

Process finished with exit code 0

  1. Put the escaping character before the single quote in the string.

In Python, the backslash is an escaping character.

So you can use it like the below:

print(‘hello I don\’t like single quote at all’)

Output:

hello I don’t like single quote at all

Concatenation of string

>>> # three time ram and once syam

>>> 3 * ‘ram’ + ‘Shyam’

2.3 Concating Strings

Indexing of Strings

Strings can be indexed (subscripted), with the first character having index 0. There is no separate character type; a character is simply a string of size one:

2.4 String

If you need a different string, you should create a new one:

>>>

>>> ‘J’ + word[1:]

‘Jython’

>>> word[:2] + ‘py’

‘Pypy’

The built-in function len() returns the length of a string:

>>>

>>> s = ‘supercalifragilisticexpialidocious’

>>> len(s)                        # this will return the length of string s

Leave a Reply

Top
error: Content is protected !!