![]() |
VOOZH | about |
# Python Program for # Creation of String # Creating a String # with single Quotes String1 = 'Welcome to the Geeks World' print("String with the use of Single Quotes: ") print(String1) # Creating a String # with double Quotes String1 = "I'm a Geek" print("\nString with the use of Double Quotes: ") print(String1) # Creating a String # with triple Quotes String1 = '''I'm a Geek and I live in a world of "Geeks"''' print("\nString with the use of Triple Quotes: ") print(String1) # Creating String with triple # Quotes allows multiple lines String1 = '''Geeks For Life''' print("\nCreating a multiline String: ") print(String1) Output: String with the use of Single Quotes: Welcome to the Geeks World String with the use of Double Quotes: I'm a Geek String with the use of Triple Quotes: I'm a Geek and I live in a world of "Geeks" Creating a multiline String: Geeks For LifeAccessing characters in Python In Python, individual characters of a String can be accessed by using the method of Indexing. Indexing allows negative address references to access characters from the back of the String, e.g. -1 refers to the last character, -2 refers to the second last character, and so on. While accessing an index out of the range will cause an IndexError. Only Integers are allowed to be passed as an index, float or other types that will cause a TypeError.
# Python Program to Access # characters of String String1 = "GeeksForGeeks" print("Initial String: ") print(String1) # Printing First character print("\nFirst character of String is: ") print(String1[0]) # Printing Last character print("\nLast character of String is: ") print(String1[-1]) Output: Initial String: GeeksForGeeks First character of String is: G Last character of String is: sString Slicing
Like other programming languages, it's possible to access individual characters of a string by using array-like indexing syntax. In this we can access each and every element of string through their index number and the indexing starts from 0. Python does index out of bound checking.
So, we can obtain the required character using syntax, string_name[index_position]:
Traceback (most recent call last): File "8a33ebbf716678c881331d75e0b85fe6.py", line 15, in <module> print x[15] IndexError: string index out of range
e a oSlicing To extract substring from the whole string then we use the syntax like
string_name[beginning: end : step]
lco oet GeHow to print single quote or double quote on screen? We can do that in the following two ways:
Hi Mr Geek. He said, "Welcome to GeeksforGeeks" Hey so happy to be here Getting Geeky, "Loving it"How to print escape character instead? If there is a requirement of printing the escape character(\) instead,then if user mention it in a string interpreter will think of it as escape character and will not print it.In order to print the escape character user have to use escape character before '\' as shown in the example.
\ is back slash