{"id":2762,"date":"2023-10-17T09:39:03","date_gmt":"2023-10-17T04:09:03","guid":{"rendered":"https:\/\/python-programs.com\/?p=2762"},"modified":"2023-11-10T11:44:43","modified_gmt":"2023-11-10T06:14:43","slug":"python-how-to-get-first-n-characters-in-a-string","status":"publish","type":"post","link":"https:\/\/python-programs.com\/python-how-to-get-first-n-characters-in-a-string\/","title":{"rendered":"Python: How to get first N characters in a string?"},"content":{"rendered":"

This article is about finding the first N characters of String where the N represents any number or int value.<\/p>\n

How to get the first N characters in a String using Python<\/h2>\n

As we know in Python String is a sequence of characters where the index numbers are associated with each character.<\/p>\n

For example : We have a String variable named String_value<\/code> which contains a String Technology i.e<\/p>\n

String_value = \u201cTechnology\u201d<\/pre>\n

Where the sequence number\/index of the first character starts with 0 and it goes on. Like<\/p>\n

Index of character \u2018T\u2019 = 0<\/p>\n

Index of character \u2018e\u2019 = 1<\/p>\n

Index of character \u2018c\u2019 = 2<\/p>\n

Index of character \u2018h\u2019 = 3<\/p>\n

Index of character \u2018n\u2019 = 4<\/p>\n

Index of character \u2018o\u2019 = 5<\/p>\n

Index of character \u2018l\u2019\u00a0 = 6<\/p>\n

Index of character \u2018o\u2019 = 7<\/p>\n

Index of character \u2018g\u2019 = 8<\/p>\n

Index of character \u2018y\u2019 = 9<\/p>\n

In Python, with the help of the [ ] (Subscript operator or Index Operator) any character of the string can be accessed just by passing the index number within it.<\/p>\n

Like String_value[i] will return i-th character of the string.<\/p>\n

For example, String_value[4] will return character \u2018n\u2019.<\/p>\n

Program to get first character of the String :<\/h3>\n
#Program:\r\n\r\nString_value = \"Technology\"\r\nFirst_char = String_value[0]\r\nprint('First character of the string is', First_char)<\/pre>\n
Output : <\/b>\r\nFirst character of the string is T<\/span><\/pre>\n

Here, just by passing index position 0 in the operator [ ], we fetched the first character of the string.<\/span><\/p>\n

Note : Like that by passing any index position in this [ ] operator, we can get the corresponding character of the string.<\/b><\/p>\n

But next we have to find first N characters simply means a substring we have to return from the original string. So lets know how to achieve that.<\/span><\/p>\n

Program to get first N characters of the String :<\/b><\/h3>\n

In the above example we just passed a single index position inside the subscript operator, beside this, the subscript operator can also take a range too.<\/span><\/p>\n

Syntax :String_VariableName [Start_IndexPosition : End_IndexPosition : Step_Size]<\/span><\/pre>\n

Where,<\/span><\/p>\n