Reputation: 151
is there any termination character like '\0' in C for string in python? we can print the string character by character using the following code in C.
while (ch[c] != '\0')
{
putchar(ch[c]);
c++;
}
Upvotes: 1
Views: 9947
Reputation: 86260
If you would like to loop through the string, you can use a for loop.
import sys
for c in ch:
sys.stdout.write(c)
but, this works just as well, except it adds a new line
print ch
This doesn't print a new line (but does add a space)
print ch,
If you need the index, you can do any of the above, but in an enumerated fashion.
for i, c in enumerate(ch):
print i, c
This gives:
0 a
1 b
2 c
3 d
For a more c-like approach, which isn't recommended, you can do this:
ch = "abcd"
i = 0
while i < len(ch):
ch[i]
i += 1
Upvotes: 1
Reputation: 2189
In python, a string is an object. It comes with attributes and methods. You cannot really compare this to a C char*
which is basically just a memory address.
You can use the len(...)
function on a string object to know its length and do whatever you want about it.
Upvotes: 2
Reputation: 369384
Python string is not nul-terminated.
Why don't you just the string?
>>> ch = 'abcd'
>>> print(ch)
abcd
Upvotes: 0